T4l0n February 2016

how to read objects continuously

I have written Objects into a .bin file, i am trying to read them into the console, but this

try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream("file.bin"))){
    for(Ser s = (Ser)ois.readObject(); s = (Ser)ois.readObject(); s!=null)
        System.out.println(s);
}catch (IOException | ClassNotFoundException e){
    e.printStackTrace();
}

gives me an error on the second line in the increment of the for loop : Type mismatch: cannot convert from Ser to boolean, how can i do this ?

Answers


Martín Muñoz del R&# February 2016

In:

for(Ser s = (Ser)ois.readObject(); s = (Ser)ois.readObject(); s!=null)

After the first ;:

; s = (Ser)ois.readObject();

Supposed to give a boolean result.

Maybe what you really want is something like:

for(Ser s = (Ser)ois.readObject(); s!=null; s = (Ser)ois.readObject())


Mark Peters February 2016

You have your loop clauses mismatched. It's

for(declarations; exit_check; increment)

In the pattern you're trying to use, you would normally do something like

for(Ser ser = null; (ser = (Ser)ois.readObject()) != null; /*blank*/) {
   //do something
}


S.Klumpers February 2016

for(Ser s = (Ser)ois.readObject(); s = (Ser)ois.readObject(); s!=null)

Should be

try {
    for(Ser s = (Ser)ois.readObject();; s = (Ser)ois.readObject())
    {
         //Code
    }
} catch(EOFException ex)
{
    //EOF found
}

Instead. In a for loop the condition should be on the second line, not on the third.

Because javac is looking for a condition at your second line and finds s, an instance of Ser, it says s cannot be converted to a boolean.

@EJP :

Contrary to what everybody seems to think here, readObject() does not return null at end of stream. It throws EOFException.

@EJP is right about the EOF, I edited my answer to include that.


EJP February 2016

The loop is wrong anyway, no point in trying to fix it. Contrary to what everybody seems to think here, readObject() does not return null at end of stream. It throws EOFException. So that is what you have to test for:

try( ObjectInputStream ois = new ObjectInputStream(new FileInputStream("file.bin"))){
    for(;;) {
        Ser s = (Ser)ois.readObject();
        System.out.println(s);
    }
} catch (EOFException exc) {
    // end of stream: OK
} catch (IOException | ClassNotFoundException e){
    e.printStackTrace();
}

Post Status

Asked in February 2016
Viewed 1,360 times
Voted 5
Answered 4 times

Search




Leave an answer