在爪哇,我有一串我想要编码的,它作为一个字阵列(在UTF8,或一些其他编码)。另外,我有一个字阵列(在一些已知的编码)和我想要将其转换成Java串。我该怎么做这些转换?

有帮助吗?

解决方案

转换从串字节[]:

String s = "some text here";
byte[] b = s.getBytes(StandardCharsets.UTF_8);

从字节[]String:

byte[] b = {(byte) 99, (byte)97, (byte)116};
String s = new String(b, StandardCharsets.US_ASCII);

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

其他提示

这里有一个解决方案,避免执行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 类。The JAVA文件 列出了支持编码.

90%的时间,这种转换是执行对流,所以你使用 读者/作家 课程。你不会逐步解码使用的字符串方法上的任意字节流-你会离开自己打开来的错误涉及多人物。

我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,the字节的信息是不正确的解释。

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

作为替代, 从Apache Commons可以使用。

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

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

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

用于解码的一系列字节到一个正常的串的消息我最后得到它的工作与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。郎。字符串 在所有。这是更多的高性能简单地铸字节到char:

完全的工作的例子:

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

如果你是 使用 大人物 如A,Æ,埃、Ç,我,Ê 可以肯定的是,只有发射值的第128Unicode字,然后这种代码也将工作UTF-8和扩展ASCII码(如cp-1252).

//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 );
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top