【发布时间】:2014-06-27 11:15:08
【问题描述】:
我从 IOStream 获取字节并将其转换为字符串。从该字符串中,我使用子字符串 api 提取序列。
ByteArray 的大小为 128 字节。如果流只包含 10 个字节并且剩余的用零填充[初始填充]。我通过传递给字符串构造函数 new String(byte[]) 并检查长度将字节数组转换为字符串。长度是128。为什么显示128?实际上它应该显示 10 字节的字符长度。 如何在转换为字符串时消除零。是否有任何 api 可以消除字节数组中的默认零。从构造的字符串创建子字符串时会产生问题。
byte[] b = { 99, 116, 101, 100, 46, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0}
System.out.println("byte length = " + b.length);
String str;
try {
str = new String(b, "UTF-8");
System.out.println("String length = " + str.length());
System.out.println(str);
System.out.println(" ## substring = " + str.substring(0));
System.out.println(" substring length = "
+ str.substring(0).length());
System.out.println("Done......");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}0, 0, 0 };
【问题讨论】:
-
从数组后面循环,直到找到 first 非零
Byte。在otherStringctor 中使用该索引。 -
-
@Boris 我无法预测它是哪个零。默认大小为零还是输入流中的零?
-
如果您说要将其分块为
128字节段,那么对于每个段,您都知道填充从末尾开始。如果您向后工作,则填充在读取第一个非零byte时结束。 -
这似乎是一个 XY 问题。您想从 InputStream 中读取数据作为文本。但是您发布的问题是关于您在尝试的解决方案中遇到的问题。 meta.stackexchange.com/a/66378