java中如何将字符串转换为字节数组
时间:2020-02-23 14:34:47 来源:igfitidea点击:
有时,我们需要将字符串转换为字节数组。
我们可以使用string的getBytes()方法来执行它,
方法语法:
public byte[] getBytes()
String getBytes示例:
package org.arpit.theitroad; public class StringBytesExample { public static void main(String[] args) { String str1 = "theitroad"; byte[] bytes=str1.getBytes(); System.out.println(str1.length()); System.out.println(bytes.length); System.out.println(bytes.toString()); } }
运行上面的程序时,我们将得到以下输出:
9 9 [B@e1641c0
GetBytes还有一个更加过载的方法
方法语法:
public byte[] getBytes(String charSetName)
它将字符串编码为指定的Charset格式。
我们可以从http://docs.oracle.com/javase/7/docs/api/java/nio/charset/charset.html读取关于charset
允许在Charset UTF-16LE和UTF-16BE中编码上面的字符串
package org.arpit.theitroad; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; public class StringBytesExample { public static void main(String[] args) { String str1 = "theitroad"; byte[] bytesDef=str1.getBytes(); byte[] bytesUTFLE = null; byte[] bytesUTFBE = null; try { bytesUTFLE = str1.getBytes("UTF-16LE"); bytesUTFBE=str1.getBytes("UTF-16BE"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } System.out.println("Encoding using default charSet"); for (int i = 0; i < bytesDef.length; i++) { System.out.print(bytesDef[i]); } System.out.println("n----------------------------------"); System.out.println("nEncoding using UTF-16LE charset"); for (int i = 0; i < bytesUTFLE.length; i++) { System.out.print(bytesUTFLE[i]); } System.out.println("n----------------------------------"); System.out.println("nEncoding using UTF-16BE charset"); for (int i = 0; i < bytesUTFBE.length; i++) { System.out.print(bytesUTFBE[i]); } } }
运行上面的程序时,我们将得到以下输出:
Encoding using default charSet 10697118975098108111103 --------------------------------- Encoding using UTF-16LE charset 10609701180970500980108011101030 --------------------------------- Encoding using UTF-16BE charset 01060970118097050098010801110103