我遇到了以下程序,它显示了意想不到的结果。
public class StringFromByte
{
public static void main(String[] args)
{
byte bytes[] = new byte[256];
for(int i = 0; i < 256; i++)
bytes[i] = (byte)i;
String str = new String(bytes);
for(int i = 0, n = str.length(); i < n; i++)
System.out.print((int)str.charAt(i) + " ");
}
}
从技术上讲,这个程序应该按顺序打印 0 到 255 之间的整数。但是,如果您运行该程序,有时它会显示此序列(0 到 255),有时它会显示其他序列。其行为未指定。这是怎么回事?
最佳答案
您正在使用的 String 构造函数使用默认字符编码。它可以将某些字节解释为多字节字符。
试试这个:
String str = new String(bytes, CharSet.forName( "ISO-8859-1" ));
另请参阅CharSet API documentation ,其中列出了标准字符集名称。
免责声明:我通常使用这个构造函数来处理 UTF-8。
关于Java问题: creating a string from a sequence of bytes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5236102/