我需要从文件中读取字节,将它们转换为字符串,对字符串进行处理,然后从字符串中获取字节,所以我有以下代码:

byte[] bFile=readFileBytes(filePath);
StringBuilder massageBuilder=new StringBuilder();

for (int i=0;i<bFile.length;i++) massageBuilder.append(bFile[i]);

String x=massageBuilder.charAt(n)+"";

...

byte b=x.getBytes();


但是最后一步没有取回字节,这是怎么回事,我想取回“ massageBuilder.charAt(n)”吗?

最佳答案

鉴于如何将原始字节添加到字符串生成器中,您无法回到原始字节。

举个例子:

byte[] bFile = "This is the input string".getBytes();
StringBuilder massageBuilder = new StringBuilder();

for (int i = 0; i < bFile.length; i++)
    massageBuilder.append(bFile[i]);


打印massageBuilder时,您得到

8410410511532105115321161041013210511011211711632115116114105110103


它们成为数字的随机序列,无法区分原始字节。结果字符串中的一个或多个字符将链接到单个输入byte。即使您知道原始文本的字符集,也仍然会因为顺序不明确而遇到麻烦。

如果使用某种分隔符,则可能会...

massageBuilder.append(bFile[i]).append("-");
//84~104~105~115~32~105~115~32~116~104~101~32~105~110~112~117~116~...


在这种情况下,您可以拆分它并重建字节数组。

10-04 21:12
查看更多