如果字节数组包含非ASCII字符,是否会创建字符串?
String s = new String(byte[] b)
将单个字节解释为 ascii 字符,很容易拒绝低于 32 和高于 126 的值。
public static boolean isPrintableAscii(byte value)
{
return (value > 32 ) && (value < 127);
}
public static String readableText(byte[] buffer, int offset, int bufferSize)
{
StringBuilder builder = new StringBuilder();
for( int index = 0; index < bufferSize; ++index)
{
byte current = buffer[offset+index];
if( isPrintableAscii(current))
{
builder.append((char)current);
}
else
{
builder.append('.');
}
}
return builder.toString();
}
当遇到不可打印的字节时,我只打印一个'。' 被十六进制转储实用程序使用了很长时间。
您可以使用new String (byte[] data, String charsetName)
传递第二个参数作为US-ASCII
No, it will not fail. However, there ways to detect non-ascii characters in a string and remove them. But Strings with non-ascii characters are perfectly fine.