❶ java怎麼將string轉換成byte數組
思路:先定義字元串,再通過getBytes()方法進行轉換數組就可以了。
參考代碼:
Strings="ZhiDao";//定義字元串
byte[]sb=s.getBytes();//把字元串轉換成數組
String的getBytes()方法是得到一個系統默認的編碼格式的位元組數組。將一個String類型的字元串中包含的字元轉換成byte類型並且存入一個byte[]數組中。
❷ java中String類型的如何轉為byte[]
一、String轉byte數組簡單版:
1、String str = "abcd";
2、byte[] bs = str.getBytes();
二、復雜版
// pros - no need to handle UnsupportedEncodingException // pros - bytes in specified
encoding scheme byte[] utf8 = "abcdefgh".getBytes(StandardCharsets.UTF_8);
System.out.println("length of byte array in UTF-8 : " + utf8.length);
System.out.println("contents of byte array in UTF-8: " + Arrays.toString(utf8));
Output : length of byte array in UTF-8 : 8 contents of byte array in UTF-8: [97, 98, 99, 100, 101, 102, 103, 104]1
反過來,將Byte數組轉化為String的方法
using System;
using System.Text;
public static string FromASCIIByteArray(byte[] characters)
{
ASCIIEncoding encoding = new ASCIIEncoding( );
string constructedString = encoding.GetString(characters);
return (constructedString);
}
·
❸ java中的字元串轉為byte類型怎麼轉
String類有提供好的方法啊,getBytes()
getBytes
public byte[] getBytes(Charset charset)
使用給定的 charset 將此 String
編碼到 byte 序列,並將結果存儲到新的 byte 數組。
此方法總是使用此字元集的默認替代 byte 數組替代錯誤輸入和不可映射字元序列。如果需要對編碼過程進行更多控制,則應該使用 CharsetEncoder
類。
參數:
charset - 用於編碼 String 的 Charset
返回:
所得 byte 數組
從以下版本開始:
1.6
❹ Java中,String類型怎麼轉換成byte類型輸出
程序如下:
String s = "fs123fdsa";//「fs123fdsa」是輸入的string變數
byte b[] = s.getBytes();//String轉換為byte[]
String t = new String(b);//bytep[]轉換為String
❺ java裡面byte數組和String字元串怎麼轉換
byte數組轉換成String可以調用String的參數為byte數組的構造方法,代碼如下:String res = new String(byte);
String轉換成byte數組可以調用String的getByte方法,代碼如下:byte[] srtbyte = str.getBytes();
❻ java裡面byte數組和String字元串怎麼轉換
java裡面byte數組和String字元串轉換有兩種方法:
1、不設定編碼方式
<prename="code"class="java">Stringstr="Hello";
byte[]srtbyte=str.getBytes();//string轉byte[]
//s
Stringres=newString(srtbyte);//byte[]轉string
2、設定編碼方式
Stringstr="hello";
byte[]srtbyte=null;
try{
srtbyte=str.getBytes("UTF-8");//string轉byte[]
Stringres=newString(srtbyte,"UTF-8");//byte[]轉string
}catch(UnsupportedEncodingExceptione){
e.printStackTrace();
}