对于我的 Java 程序,我获得了需要写入文件的字节数组列表。我之前尝试过的是
FileWriter fw = new FileWriter("file.out");
BufferedWriter bw = new BufferedWriter(fw);
bw.write(new String(data));
bw.flush();
数据是列表中的一个字节[]。 因为我将其转换为字符串,所以我认为我失去了二进制文件的正确性。
所以我现在正在尝试使用 FileOutputStream。
File myFile = new File("file.out");
FileOutputStream fos = new FileOutputStream(myFile);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bos.write(data);
bos.flush();
数据也是列表中的一个 byte[]。
我的问题是,我现在如何检查我编写的文件是否确实是二进制正确的。如果我将文件的每一行读取为 byte[] 并将其与输入进行比较,它会完全相同吗?
最佳答案
将数组写入文件:
List<byte[]> list = new ArrayList<byte[]>();
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filePath));
out.writeObject(list);
然后从同一文件中读回数组:
ObjectInputStream in = new ObjectInputStream(new FileInputStream(filePath));
List<byte[]> byteList = (List<byte[]>) in.readObject();
注意 - 这不包括流的处理、异常处理等
关于java - 如何将二进制正确写入文件并证明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47618874/