一、字節數組轉String亂碼
當將字節數組轉換成String時,經常會出現亂碼的情況。這是由於編碼方式不一致導致的。需要在轉換之前指定編碼方式。例如,在將UTF-8編碼的字節數組轉換成String時,應該使用如下代碼:
byte[] byteArray = {72, 101, 108, 108, 111, 32, -26, -106, -121, -25, -67, -92, -28, -72, -117}; String str = new String(byteArray, "UTF-8"); System.out.println(str); // "Hello 世界"
如果沒有指定編碼方式,則使用平台默認的編碼方式。在不同的平台上,可能會有不同的默認編碼方式,因此應該盡量避免使用默認編碼方式。
二、字節數組怎麼轉String
將字節數組轉換成String,可以使用String類的構造函數,如下所示:
byte[] byteArray = {72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100}; String str = new String(byteArray); System.out.println(str); // "Hello World"
在此例中,將一個字節數組轉換成了一個ASCII字符串。
三、字節數組轉inputstream
將字節數組轉換成InputStream,可以使用ByteArrayInputStream類,如下所示:
byte[] byteArray = {72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100}; ByteArrayInputStream inputStream = new ByteArrayInputStream(byteArray); int data; while ((data = inputStream.read()) != -1) { System.out.println((char) data); }
在此例中,使用ByteArrayInputStream將字節數組轉換成了InputStream,並按字節讀取了數據並輸出。
四、字節數組轉int
將字節數組轉換成int,可以使用ByteBuffer類,如下所示:
byte[] byteArray = {0x12, 0x34, 0x56, 0x78}; int num = ByteBuffer.wrap(byteArray).getInt(); System.out.println(num); // 305419896
在此例中,將一個字節數組轉換成了一個int類型的數據。
五、字節數組轉換成字符串
將字節數組轉換成字符串,可以使用Base64編碼,如下所示:
byte[] byteArray = {72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100}; String str = Base64.getEncoder().encodeToString(byteArray); System.out.println(str); // "SGVsbG8gV29ybGQ="
在此例中,使用Base64編碼將字節數組轉換成字符串。
六、字節數組轉16進制
將字節數組轉換成16進制字符串,可以使用BigInteger類,如下所示:
byte[] byteArray = {0x12, 0x34, 0x56, 0x78}; String hexStr = new BigInteger(1, byteArray).toString(16); System.out.println(hexStr); // "12345678"
在此例中,將一個字節數組轉換成了一個字符串類型的16進制數。
七、字節數組轉json
將字節數組轉換成JSON格式,可以使用Jackson庫,如下所示:
byte[] byteArray = {123, 34, 110, 97, 109, 101, 34, 58, 34, 74, 111, 104, 110, 34, 125}; ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(byteArray); System.out.println(node.get("name").asText()); // "John"
在此例中,將一個字節數組轉換成了一個JSON對象,並按屬性讀取了其中的數據。
八、字節數組轉為輸入流
將字節數組轉換成InputStream,可以使用ByteArrayInputStream類,如下所示:
byte[] byteArray = {72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100}; InputStream inputStream = new ByteArrayInputStream(byteArray); int data; while ((data = inputStream.read()) != -1) { System.out.println((char) data); }
在此例中,使用ByteArrayInputStream將字節數組轉換成了InputStream,並按字節讀取了數據並輸出。
九、字節數組轉化為字符串
將字節數組轉換成String類型的字符串,直接使用String類的構造函數即可:
byte[] byteArray = {72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100}; String str = new String(byteArray); System.out.println(str); // "Hello World"
在此例中,將一個字節數組轉換成了一個ASCII字符串。
十、字節數組轉浮點數
將字節數組轉換成浮點數,可以使用ByteBuffer類,如下所示:
byte[] byteArray = {63, -93, -23, -48}; float num = ByteBuffer.wrap(byteArray).getFloat(); System.out.println(num); // 0.12345679
在此例中,將一個字節數組轉換成了一個float類型的數據。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/245280.html