如何将string转换为Java中的UTF8字节数组

在Java中,我有一个string,我想编码为一个字节数组(UTF8,或其他编码)。 另外,我有一个字节数组(在一些已知的编码),我想转换成一个Javastring。 我如何做这些转换?

从string转换为字节[]:

String s = "some text here"; byte[] b = s.getBytes("UTF-8"); 

从byte []转换为String:

 byte[] b = {(byte) 99, (byte)97, (byte)116}; String s = new String(b, "US-ASCII"); 

当然,你应该使用正确的编码名称。 我的例子使用了“US-ASCII”和“UTF-8”这两个最常见的编码。

这里有一个解决scheme可以避免为每个转换执行Charset查找:

 import java.nio.charset.Charset; private final Charset UTF8_CHARSET = Charset.forName("UTF-8"); String decodeUTF8(byte[] bytes) { return new String(bytes, UTF8_CHARSET); } byte[] encodeUTF8(String string) { return string.getBytes(UTF8_CHARSET); } 
 String original = "hello world"; byte[] utf8Bytes = original.getBytes("UTF-8"); 

您可以直接通过String(byte [],String)构造函数和getBytes(String)方法进行转换。 Java通过Charset类公开了可用的字符集。 JDK文档列出了支持的编码 。

90%的时间,这样的转换是在stream上执行的,所以你可以使用Reader / Writer类。 您不会在任意字节stream上使用string方法进行增量式解码 – 您可以自行打开涉及多字节字符的错误。

我的tomcat7实现接受string为ISO-8859-1; 尽pipeHTTP请求的内容types。 当试图正确解释“é”这样的字符时,下面的解决scheme适用于我。

 byte[] b1 = szP1.getBytes("ISO-8859-1"); System.out.println(b1.toString()); String szUT8 = new String(b1, "UTF-8"); System.out.println(szUT8); 

当试图将string解释为US-ASCII时,字节信息未被正确解释。

 b1 = szP1.getBytes("US-ASCII"); System.out.println(b1.toString()); 

作为替代,可以使用来自Apache Commons的StringUtils 。

  byte[] bytes = {(byte) 1}; String convertedString = StringUtils.newStringUtf8(bytes); 

要么

  String myString = "example"; byte[] convertedBytes = StringUtils.getBytesUtf8(myString); 

如果你有非标准的字符集,可以相应地使用getBytesUnchecked()或newString() 。

如果您使用的是7位ASCII或ISO-8859-1(一个非常常见的格式),那么您根本就不必创build一个新的java.lang.String 。 简单地将字节转换为char,性能要高得多:

完整的工作示例:

 for (byte b : new byte[] { 43, 45, (byte) 215, (byte) 247 }) { char c = (char) b; System.out.print(c); } 

如果您使用扩展字符(如Ä,Æ,Å,Ç,Ï,Ê), 确保唯一传输的值是前128个Unicode字符,则此代码也适用于UTF-8和扩展ASCII (如cp-1252)。

为了将一系列的字节解码成一个正常的string消息,我终于用UTF-8编码来处理这个代码:

 /* Convert a list of UTF-8 numbers to a normal String * Usefull for decoding a jms message that is delivered as a sequence of bytes instead of plain text */ public String convertUtf8NumbersToString(String[] numbers){ int length = numbers.length; byte[] data = new byte[length]; for(int i = 0; i< length; i++){ data[i] = Byte.parseByte(numbers[i]); } return new String(data, Charset.forName("UTF-8")); } 
 //query is your json DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost("http://my.site/test/v1/product/search?qy="); StringEntity input = new StringEntity(query, "UTF-8"); input.setContentType("application/json"); postRequest.setEntity(input); HttpResponse response=response = httpClient.execute(postRequest); 

我不能评论,但不想开始一个新的线程。 但是这不起作用。 简单的往返:

 byte[] b = new byte[]{ 0, 0, 0, -127 }; // 0x00000081 String s = new String(b,StandardCharsets.UTF_8); // UTF8 = 0x0000, 0x0000, 0x0000, 0xfffd b = s.getBytes(StandardCharsets.UTF_8); // [0, 0, 0, -17, -65, -67] 0x000000efbfbd != 0x00000081 

编码之前和之后,我会需要b []相同的数组它不是(这引用到第一个答案)。

 Charset UTF8_CHARSET = Charset.forName("UTF-8"); String strISO = "{\"name\":\"א\"}"; System.out.println(strISO); byte[] b = strISO.getBytes(); for (byte c: b) { System.out.print("[" + c + "]"); } String str = new String(b, UTF8_CHARSET); System.out.println(str); 
 Reader reader = new BufferedReader( new InputStreamReader( new ByteArrayInputStream( string.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8)); 

非常晚,但我刚刚遇到这个问题,这是我的修复:

 private static String removeNonUtf8CompliantCharacters( final String inString ) { if (null == inString ) return null; byte[] byteArr = inString.getBytes(); for ( int i=0; i < byteArr.length; i++ ) { byte ch= byteArr[i]; // remove any characters outside the valid UTF-8 range as well as all control characters // except tabs and new lines if ( !( (ch > 31 && ch < 253 ) || ch == '\t' || ch == '\n' || ch == '\r') ) { byteArr[i]=' '; } } return new String( byteArr ); }