Adrian Perkovic
Adrian Perkovic

Reputation: 3

Java not reading all object from file

So I have a real strange bug, I get my objects into a arraylist, write them out to see if everything is there, everything checks out, i write them down into a file, eveything is there when I open the file, but when i go on to read them some objects are for unknow reasons not read, like that entry isnt exisitng in the file, but I can see in the file that they are there. Anyone know that I'm missing here?

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class ReadWriteTD {

    public static void write(ArrayList<Tokendata> list) {
        try {
            FileOutputStream f = new FileOutputStream(new File("src/resources/TokenProfiles"));
            ObjectOutputStream o = new ObjectOutputStream(f);

            // Write objects to file

            list.forEach(a -> {
                try {
                    o.writeObject(a);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            });


            o.close();
            f.close();



        } catch (FileNotFoundException e) {
            System.out.println("File not found");
        } catch (IOException e) {
            System.out.println("Error initializing stream");
        }

    }


    public static ArrayList<Tokendata> read() {
        ArrayList<Tokendata> list = new ArrayList<Tokendata>();

        try {

            FileInputStream fi = new FileInputStream(new File("src/resources/TokenProfiles"));
            ObjectInputStream oi = new ObjectInputStream(fi);           

            Boolean cond = true;
            while(cond){
                if(oi.readObject() != null) 
                    list.add((Tokendata) oi.readObject());
                else cond=false;
            }

            oi.close();
            fi.close();

    }catch(Exception e){

    }
    //list.forEach(a -> System.out.print(a.toString()));
        return list;

    }

}   

Upvotes: 0

Views: 403

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500065

This is the problem:

if(oi.readObject() != null)
   list.add((Tokendata) oi.readObject());

That's calling readObject() twice per iteration. The result of the first call is ignored other than to check whether or not it's null. You just want something like:

Object obj;
while ((obj = oi.readObject()) != null) {
    list.add((Tokendata) obj);
}

No need for your cond variable, and now you're only calling readObject once per iteration.

Upvotes: 8

Related Questions