繁体   English   中英

如何存储字节并将其读回数组

[英]How to store bytes and read them back to an array

我试图将一个数字(字节)列表存储到一个文件中,以便可以将它们检索到一个字节[]中。

59 20 60 21 61 22 62 23 63 24 64 25 65 26 66 27 67 28 68 29 
67 30 66 31 65 32 64 33 63 34 62 35 61 36 60 37 59 38
66 29 65 30 64 31 63 32 62 33 61 34 60 35 59 36 58 37
65 28 64 29 63 30 62 31 61 32 60 33 59 34 58 35 57 36...

我尝试将它们保存到文本文件中,但相关代码似乎无法正确读取它。

    try {
        File f = new File("cube_mapping2.txt");
        array = new byte[file.size()]
        FileInputStream stream = new FileInputStream(f);
        stream.read(array);
    } catch (Exception e) {
        e.printStackTrace();
    }

是否有保存文件的正确方法,以便FileInputReader.read(byte[] buffer)用我的字节填充数组?

我会使用Scanner 像这样:

public static void main(String[] args) throws IOException {
    InputStream stream = new FileInputStream("cube_mapping2.txt");
    Scanner s = new Scanner(stream);
    List<Byte> bytes = new ArrayList<Byte>();
    while (s.hasNextByte()) {
        bytes.add(s.nextByte());
    }
    System.out.println(bytes);
}

我在包含您确切输入的文件上对此进行了测试,并且可以正常工作。 输出为:

[59, 20, 60, 21, 61, 22, 62, 23, 63, 24, 64, 25, 65, 26, 66, 27, 67, 28, 68, 29, 67, 30, 66, 31, 65, 32, 64, 33, 63, 34, 62, 35, 61, 36, 60, 37, 59, 38, 66, 29, 65, 30, 64, 31, 63, 32, 62, 33, 61, 34, 60, 35, 59, 36, 58, 37, 65, 28, 64, 29, 63, 30, 62, 31, 61, 32, 60, 33, 59, 34, 58, 35, 57, 36]

FileInputStream适用于二进制文件。 你的代码将发布从二进制文件阅读,但并不完全正确,因为stream.read(数组)中读取数组的长度; 它不会保证读取整个数组。 read(array)的返回值是实际读取的字节数。 为了确保获得所有想要的数据,您需要将read()调用置于循环中。

要回答您的实际问题:使用FileOutputStream.write(array)以stream.read(array)能够将其读回的方式写入文件,请使用FileOutputStream.write(array)。

如果您对文本文件而不是二进制文件感到满意,请使用@Bohemian的答案。

array = new byte[file.size()]

这是否意味着每个数字都没有空间存储单独的标记? 根据您的字节数组,如果它们中的每个仅是两个空格,则可以使用两个空格的临时字节数组来读取存储在文件中的每个字节。 就像是

byte[] temp = new byte[2];
stream.read(temp);

可以确保一一读取字节数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM