0

我的字节数组输出在输出中将未使用的位(默认)值显示为 0。
如何从结果中删除它们?

byte[] data=new byte[20];
int cl; 
try {
    FileInputStream fs = new FileInputStream("c:/abc.txt");

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    while ((cl = fs.read(data,0,data.length)) != -1)
        os.write(data,0,cl);
    os.flush();
}

System.out.println(Arrays.toString(data));

这是我的代码的输出:

[104, 105, 32, 119, 101, 108, 99, 111, 109, 101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
4

2 回答 2

0

你确定你不是这个意思?

//...
System.out.println(Arrays.toString(os.toByteArray()));

您正在打印用于从文件中以字节块形式检索数据的临时数组的内容。通过调用字节数组流的toByteArray方法(参见ByteArrayOutputStream#toByteArray),您可以得到假想的结果,即具有适当数组大小的文件的全部内容。

在较小的问题上,您在数据数组中找到的零是在创建数组时定义的。它们没有被覆盖,因为文件大小不足以将所有索引至少写入一次。并引用InputStream#read

在每种情况下,元素 b[0] 到 b[off] 和元素 b[off+len] 到 b[b.length-1] 都不受影响。

于 2013-06-25T15:40:35.220 回答
0

如果只写入 20 个字节。

    if ((cl = fs.read(data,0,data.length)) != -1) {
        while (cl > 1 && data[cl - 1] == 0)
            --cl;
        os.write(data,0,cl);
    }

尽管该文件似乎是一个文本文件,并且是用二进制零编写的。如果您确定始终写入 20 个字节的数组,并且尾随字节全部为 0,则可以将第一个字节if再次转换为while.

于 2013-06-25T15:29:02.343 回答