0

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;

    }

}   
0

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.