Java中将String转换为字节数组的3种方式

来源:互联网 发布:驱动精灵linux版 编辑:程序博客网 时间:2024/06/08 14:59

今天,我将讨论程序员的常见任务之一,将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

阅读全文
0 0
原创粉丝点击