gpt4 book ai didi

java - FileInputStream.available() 返回字节,但 ObjectInputStream.available() 返回 0

转载 作者:行者123 更新时间:2023-11-30 06:56:36 40 4
gpt4 key购买 nike

我遇到了一个我似乎不明白的奇怪问题。我正在制作一个从文件中读取数据的程序。但是当我读取数据时,我立即收到 EOFException。

所以我用 .available() 检查文件是否为空。我得到了一个奇怪的结果。 FileInputStream 表示文件已满(249 字节),但 ObjectInputStream 表示文件为空(或无法读取)。

EOFException 位于:“intsignatureSize = ois.readInt();”

        FileInputStream fin = new FileInputStream("input(signedbyLK).ext");
System.out.println("fin available: " + fin.available());

ObjectInputStream ois = new ObjectInputStream(fin);
System.out.println("ois avaiable: " + ois.available());

int signatureSize = ois.readInt();
byte[] sigBytes = (byte[]) ois.readObject();
String text = (String) ois.readObject();
ois.close();

编辑:我将内容添加到文件中,如下所示:

        File newFile = new File("input(signedbyLK).ext");
newFile.createNewFile();

System.out.println("Succesfully created new file: " + newFile.getName());

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(newFile));
oos.writeObject(sigBytes.length);
oos.writeObject(sigBytes);
oos.writeObject(readInput());
oos.close();

最佳答案

这是javadoc所说的

Any attempt to read object data which exceeds the boundaries of the custom data written by the corresponding writeObject method will cause an OptionalDataException to be thrown with an eof field value of true. Non-object reads which exceed the end of the allotted data will reflect the end of data in the same way that they would indicate the end of the stream: bytewise reads will return -1 as the byte read or number of bytes read, and primitive reads will throw EOFExceptions. If there is no corresponding writeObject method, then the end of default serialized data marks the end of the allotted data.

此外,您需要按照序列化时的顺序读取对象输入流

关于java - FileInputStream.available() 返回字节,但 ObjectInputStream.available() 返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41665197/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com