1

I have a class to write customer objects into an arraylist and write this to a file.Each write will append to the end of the file. But when I try to read all of the data in the file it only displays the first object stored in my arraylist.

public void readFromFile(){
    ArrayList <Customer> list;

    try{
        final String FILENAME = "..//Files//customer.bin";


        FileInputStream fi = new FileInputStream(FILENAME);
        ObjectInputStream os = new ObjectInputStream(fi);

        list = (ArrayList)os.readObject();

            for(Customer cus : list){
                System.out.println(cus);
            }
            os.close();
            fi.close();         
    }

How can I display all the data in the file and not just the first write??

 public void writeToFile(){

    if(customerList instanceof Serializable){
    try{
            final String FILENAME = "..//Files//customer.bin";


            FileOutputStream fo = new FileOutputStream(FILENAME,true);
            ObjectOutputStream os = new ObjectOutputStream(fo);

            os.writeObject(customerList);

            os.close();
            fo.close(); 
        }

    catch(FileNotFoundException e){
        System.out.println(e.getMessage());
    }
    catch(IOException io){
        System.out.println("Error initaling stream...");
    }
    catch(Exception w){
        System.out.println(w.getMessage());
    }
  } 
}
James F
  • 130
  • 1
  • 10
  • You show us the read but you state that the problem is in the write... How do you append binary data? – Nir Alfasi Oct 30 '17 at 19:39
  • Just added the write method now. – James F Oct 30 '17 at 19:45
  • I'm guessing that each time I start my program and add customers,I'm adding a new arraylist thats written into the file? – James F Oct 30 '17 at 20:01
  • If you want to keep it clean (and avoid potential errors), each time you're writing - delete the content of the file first and only then write the new content into it. Doing it is easy: `new File(FILENAME).delete();` – Nir Alfasi Oct 30 '17 at 21:36
  • Second, you don't provide details about your problem: do you see any error? if so in which method/line ? what is the stacktrace? – Nir Alfasi Oct 30 '17 at 21:38
  • Thanks alfasin, I found a solution based on that :) I can now read the file at the start ==> put the data into arraylist ==> then rewrite over file & repeat process.Cheers mate – James F Oct 30 '17 at 23:56
  • Glad that it helped! – Nir Alfasi Oct 31 '17 at 00:00
  • @EJP I'm not sure that it's appending to `ObjectOutputStream`, it looks like it's about appending to a (binary) file which is less trivial (unless you re-write the whole thing). – Nir Alfasi Oct 31 '17 at 00:01

0 Answers0