Guido
Guido

Reputation: 1171

FileInputStream.available() returns bytes but ObjectInputStream.available() returns 0

I ran into a weird problem which I don't seem to understand. I'm making a program which reads data from a file. But when I do read data, I immediately receive an EOFException.

So I checked with .available() if the file was empty or not. And I got a weird result. The FileInputStream said that the file was filled (249 bytes), but the ObjectInputStream said that the file is empty (or can't be read).

EOFException at: "int signatureSize = 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();

EDIT: I'm adding content to the file like this:

        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();

Upvotes: 1

Views: 732

Answers (1)

Biu
Biu

Reputation: 1076

Here is what the javadoc says

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.

Also, you need to read the object input stream in the same order as when you serialized it

Upvotes: 1

Related Questions