一、從byte數組轉string方法
在Java中,有兩種方式將byte數組轉換成String類型:
第一種方式是使用String類的構造函數,傳入byte數組作為參數:
byte[] bytes = { 97, 98, 99 }; String str = new String(bytes); System.out.println(str); // 輸出"abc"
第二種方式是使用Base64類的靜態方法,將byte數組轉換成Base64編碼的字元串,然後再使用String類的構造函數將其轉換成String類型:
byte[] bytes = { 97, 98, 99 }; String str = new String(Base64.getEncoder().encode(bytes)); System.out.println(str); // 輸出"YWJj"
注意,在第二種方式中,Base64編碼後得到的字元串可能會比原byte數組的長度大,因此在轉換回byte數組時需要使用Base64解碼。
二、string和byte怎麼互轉
在Java中,將String類型轉換成byte數組的方法有兩種:
第一種方式是使用String類的getBytes()方法,該方法將字元串轉換成默認編碼格式的byte數組:
String str = "abc"; byte[] bytes1 = str.getBytes(); System.out.println(Arrays.toString(bytes1)); // 輸出"[97, 98, 99]"
第二種方式是使用指定的編碼格式將字元串轉換成byte數組:
String str = "abc"; byte[] bytes2 = str.getBytes("UTF-8"); System.out.println(Arrays.toString(bytes2)); // 輸出"[97, 98, 99]"
將byte數組轉換成String類型的方法在前面已經進行了詳細的介紹,這裡不再贅述。
三、怎麼將byte轉換成string
在Java中,可以使用類庫中的Byte類將byte類型轉換成String類型。
Byte類提供了以下兩種方法,分別將byte類型轉換成十進位字元串和十六進位字元串:
byte b = 65; String str1 = Byte.toString(b); // 十進位表示 String str2 = String.format("%02x", b); // 十六進位表示 System.out.println(str1); // 輸出"65" System.out.println(str2); // 輸出"41"
需要注意的是,在將byte類型轉換成String類型時,需要使用Byte類提供的相應方法將其轉換成包裝類後再使用toString()方法進行轉換,否則會出現編譯錯誤。
四、將byte數組轉化為string
在將byte數組轉換成String類型時,需要注意編碼格式的問題。
如果不指定編碼格式,則默認使用平台的默認編碼格式。例如,在Windows平台下,默認使用的是GBK編碼格式,因此可能會出現亂碼現象。
如果明確知道byte數組的編碼格式,可以使用String的構造函數進行轉換。例如,如果byte數組使用UTF-8編碼格式編碼:
byte[] bytes = { -26, -75, -117, -24, -81, -107 }; String str1 = new String(bytes, "UTF-8"); System.out.println(str1); // 輸出"你好"
如果不知道byte數組的編碼格式,可以使用CharsetDetector類進行檢測:
byte[] bytes1 = { -26, -75, -117, -24, -81, -107 }; byte[] bytes2 = { -25, -102, -79, -27, -122, -77 }; CharsetDetector detector = new CharsetDetector(); detector.setText(bytes1); CharsetMatch match = detector.detect(); String str1 = new String(bytes1, match.getName()); detector.setText(bytes2); match = detector.detect(); String str2 = new String(bytes2, match.getName()); System.out.println(str1); // 輸出"你好" System.out.println(str2); // 輸出"こんにちは"
需要注意的是,CharsetDetector類需要導入相應的類庫,可以通過Maven等工具進行管理。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/239760.html