【发布时间】:2008-09-18 00:11:21
【问题描述】:
在 Java 中,我有一个字符串,我想将它编码为一个字节数组(在 UTF8 或其他编码中)。或者,我有一个字节数组(在一些已知的编码中),我想将它转换为 Java 字符串。如何进行这些转换?
【问题讨论】:
标签: java string encoding character-encoding
在 Java 中,我有一个字符串,我想将它编码为一个字节数组(在 UTF8 或其他编码中)。或者,我有一个字节数组(在一些已知的编码中),我想将它转换为 Java 字符串。如何进行这些转换?
【问题讨论】:
标签: java string encoding character-encoding
从String 转换为byte[]:
String s = "some text here";
byte[] b = s.getBytes(StandardCharsets.UTF_8);
从byte[] 转换为String:
byte[] b = {(byte) 99, (byte)97, (byte)116};
String s = new String(b, StandardCharsets.US_ASCII);
当然,您应该使用正确的编码名称。我的示例使用了 US-ASCII 和 UTF-8,这两种常用的编码。
【讨论】:
UTF-8而不是utf8(我一直用)?
这是一个避免每次转换都执行字符集查找的解决方案:
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);
}
【讨论】:
StandardCharsets.UTF_8 以恒定方式访问 UTF-8 字符集。
String original = "hello world";
byte[] utf8Bytes = original.getBytes("UTF-8");
【讨论】:
您可以直接通过String(byte[], String) 构造函数和getBytes(String) 方法进行转换。 Java 通过Charset 类公开可用的字符集。 JDK 文档lists supported encodings。
90% 的情况下,此类转换是在流上执行的,因此您将使用 Reader/Writer 类。您不会在任意字节流上使用 String 方法进行增量解码 - 您可能会遇到涉及多字节字符的错误。
【讨论】:
UTF-8 中的字符串进行编码和解码,那么多字节字符有什么问题?
我的 tomcat7 实现接受字符串为 ISO-8859-1;尽管 HTTP 请求的内容类型。在尝试正确解释像 'é' 这样的字符时,以下解决方案对我有用。
byte[] b1 = szP1.getBytes("ISO-8859-1");
System.out.println(b1.toString());
String szUT8 = new String(b1, "UTF-8");
System.out.println(szUT8);
尝试将字符串解释为 US-ASCII 时,字节信息未正确解释。
b1 = szP1.getBytes("US-ASCII");
System.out.println(b1.toString());
【讨论】:
StandardCharSets.UTF_8 和 StandardCharSets.ISO_8859_1。
作为替代方案,可以使用来自 Apache Commons 的 StringUtils。
byte[] bytes = {(byte) 1};
String convertedString = StringUtils.newStringUtf8(bytes);
或
String myString = "example";
byte[] convertedBytes = StringUtils.getBytesUtf8(myString);
如果您有非标准字符集,您可以相应地使用getBytesUnchecked() 或newString()。
【讨论】:
我无法发表评论,但不想开始新的话题。但这行不通。一次简单的往返:
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[] 相同的数组,但它不是(这个指向第一个答案)。
【讨论】:
为了将一系列字节解码为普通的字符串消息,我终于用 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"));
}
【讨论】:
如果您使用 7 位 ASCII 或 ISO-8859-1(一种非常常见的格式),那么您根本不必创建新的 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)。
【讨论】:
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);
【讨论】:
//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);
【讨论】:
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 );
}
【讨论】: