Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList? -


i writing program in java displays range of afterschool clubs (e.g. football, hockey - entered user). clubs added following arraylist:

private arraylist<club> clubs = new arraylist<club>(); 

by followng method:

public void addclub(string clubname) {     club club = findclub(clubname);     if (club == null)         clubs.add(new club(clubname)); } 

'club' class constructor - name:

public class club {      private string name;      public club(string name) {         this.name = name;     }      //there more methods in program don't affect query.. } 

my program working - lets me add new club object arraylist, can view arraylist, , can delete want etc.

however, want save arraylist (clubs) file, , want able load file later , same arraylist there again.

i have 2 methods (see below), , have been trying working havent had anyluck, or advice appreciated.

save method (filename chosen user)

public void save(string filename) throws filenotfoundexception {     string tmp = clubs.tostring();     printwriter pw = new printwriter(new fileoutputstream(filename));     pw.write(tmp);     pw.close(); } 

load method (current code wont run - file string needs club?

public void load(string filename) throws filenotfoundexception {     fileinputstream filein = new fileinputstream(filename);     scanner scan = new scanner(filein);     string loadedclubs = scan.next();     clubs.add(loadedclubs); } 

i using gui run application, , @ moment, can click save button allows me type name , location , save it. file appears , can opened in notepad displays club@c5d8jdj (for each club in list)

as exercise, suggest doing following:

public void save(string filename) throws filenotfoundexception {     printwriter pw = new printwriter(new fileoutputstream(filename));     (club club : clubs)         pw.println(club.getname());     pw.close(); } 

this write name of each club on new line in file.

soccer chess football volleyball ... 

i'll leave loading you. hint: wrote 1 line @ time, can read 1 line @ time.

every class in java extends object class. such can override methods. in case, should interested tostring() method. in club class, can override print message class in format you'd like.

public string tostring() {     return "club:" + name; } 

you change above code to:

public void save(string filename) throws filenotfoundexception {     printwriter pw = new printwriter(new fileoutputstream(filename));     (club club : clubs)          pw.println(club); // call tostring() on club, club.tostring()     pw.close(); } 

Comments