今天,我將討論程式員的常見任務之一,將String轉換為位元組數組。這樣做可能有多種原因(將內容儲存到檔案,通過網路發送或其他原因)。假設你有一個字串“abcd”,並且你想把它轉換成位元組數組,你會怎樣做。記住,String是由char數組構成的,所以它涉及到字元到位元組的轉換。值得慶幸的是,Java提供了一種方便的getBytes()方法來將String轉換為Java中的位元組數組,但不幸的是,許多開發人員使用方式不正確。大概近70%使用getBytes()方法沒有指定字元編碼,而是使用平台預設字元編碼。這樣做大多數可以工作,但是容易出錯,如果平台的字元編碼與預期的編碼不匹配,則會產生錯誤的結果。
String to byte array using getBytes()
// converts String to bytes using platform's default character encoding, // in Eclipse it's Cp1252 // in Linux it could be something else byte[] ascii = "abcdefgh".getBytes(); System.out.println("platform's default character encoding : " + System.getProperty("file.encoding")); System.out.println("length of byte array in default encoding : " + ascii.length); System.out.println("contents of byte array in default encoding: " + Arrays.toString(ascii)); Output : platform's default character encoding : Cp1252 length of byte array in default encoding : 8 contents of byte array in default encoding: [97, 98, 99, 100, 101, 102, 103, 104]
備忘:
1)如果不指定任何字元編碼,則使用平台預設編碼將字元轉換為位元組。
2)您可以使用System.getProperty(“file.encoding”)查看平台的預設字元編碼;這將返回JVM啟動並執行機器的預設字元編碼。
3)當心,您的代碼可能在一個環境中運行沒有問題,但不能保證在其它環境下同樣可以運行。這就是為什麼你不應該依賴預設字元編碼。
4)位元組數組的長度可能與String的長度不一致,這取決於字元編碼。
String to byte array using getBytes(“encoding)
// convert String to bytes of specified character encoding but// also throw checked UnsupportedEncodingException, which pollutes the code try { byte[] utf16 = "abcdefgh".getBytes("UTF-16"); System.out.println("contents of byte array in UTF-16 encoding: " + Arrays.toString(utf16)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } Output : length of byte array in UTF-16 charater encoding : 18 contents of byte array in UTF-16 encoding: [-2, -1, 0, 97, 0, 98, 0, 99, 0, 100, 0, 101, 0, 102, 0, 103, 0, 104]
備忘:
1)這種方式比上面例子更好,但是拋出一個檢查的異常 java.io.UnsupportedEncodingException,防止字元編碼字串有錯,或者指定不支援Java的字元編碼。
2)返回指定的字元編碼的位元組數組
3)您可以看到位元組數組的長度與String中的字元數不同,就像上一個例子中的那樣,因為UTF-16編碼佔用至少2位元組來編碼字元。
String to byte array using getBytes(Charset)
// return bytes in UTF-8 character encoding // 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)這是將String轉換為Java中的位元組數組的最佳方法。
2)這不會引發java.io.UnsupportedEncodingException異常
3)牢記,StandarhardCasets類只能從Java 7起開始提供。
原文:http://www.java67.com/2017/10/3-ways-to-convert-string-to-byte-array-in-java.html