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

后端 未结 6 1468
时光取名叫无心
时光取名叫无心 2020-11-27 15:05

I am writing a program in Java which displays a range of afterschool clubs (E.G. Football, Hockey - entered by user). The clubs are added into the following ArrayList<

相关标签:
6条回答
  • 2020-11-27 15:25

    As an exercise, I would suggest doing the following:

    public void save(String fileName) throws FileNotFoundException {
        PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
        for (Club club : clubs)
            pw.println(club.getName());
        pw.close();
    }
    

    This will write the name of each club on a new line in your file.

    Soccer
    Chess
    Football
    Volleyball
    ...
    

    I'll leave the loading to you. Hint: You wrote one line at a time, you can then read one line at a time.

    Every class in Java extends the Object class. As such you can override its methods. In this case, you should be interested by the toString() method. In your Club class, you can override it to print some message about the class in any format you'd like.

    public String toString() {
        return "Club:" + name;
    }
    

    You could then change the above code to:

    public void save(String fileName) throws FileNotFoundException {
        PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
        for (Club club : clubs)
             pw.println(club); // call toString() on club, like club.toString()
        pw.close();
    }
    
    0 讨论(0)
  • 2020-11-27 15:32

    In Java 8 you can use Files.write() method with two arguments: Path and List<String>, something like this:

    List<String> clubNames = clubs.stream()
        .map(Club::getName)
        .collect(Collectors.toList())
    
    try {
        Files.write(Paths.get(fileName), clubNames);
    } catch (IOException e) {
        log.error("Unable to write out names", e);
    }
    
    0 讨论(0)
  • 2020-11-27 15:40

    This might work for you

    public void save(String fileName) throws FileNotFoundException {
    FileOutputStream fout= new FileOutputStream (fileName);
    ObjectOutputStream oos = new ObjectOutputStream(fout);
    oos.writeObject(clubs);
    fout.close();
    }
    

    To read back you can have

    public void read(String fileName) throws FileNotFoundException {
    FileInputStream fin= new FileInputStream (fileName);
    ObjectInputStream ois = new ObjectInputStream(fin);
    clubs= (ArrayList<Clubs>)ois.readObject();
    fin.close();
    }
    
    0 讨论(0)
  • 2020-11-27 15:42

    You should use Java's built in serialization mechanism. To use it, you need to do the following:

    1. Declare the Club class as implementing Serializable:

      public class Club implements Serializable {
          ...
      }
      

      This tells the JVM that the class can be serialized to a stream. You don't have to implement any method, since this is a marker interface.

    2. To write your list to a file do the following:

      FileOutputStream fos = new FileOutputStream("t.tmp");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(clubs);
      oos.close();
      
    3. To read the list from a file, do the following:

      FileInputStream fis = new FileInputStream("t.tmp");
      ObjectInputStream ois = new ObjectInputStream(fis);
      List<Club> clubs = (List<Club>) ois.readObject();
      ois.close();
      
    0 讨论(0)
  • 2020-11-27 15:44
    ObjectOutputStream.writeObject(clubs)
    ObjectInputStream.readObject();
    

    Also, you 'add' logic is logically equivalent to using a Set instead of a List. Lists can have duplicates and Sets cannot. You should consider using a set. After all, can you really have 2 chess clubs in the same school?

    0 讨论(0)
  • 2020-11-27 15:50

    To save and load an arraylist of public static ArrayList data = new ArrayList ();

    I used (to write)...

    static void saveDatabase() {
    try {
    
            FileOutputStream fos = new FileOutputStream("mydb.fil");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(data);
            oos.close();
            databaseIsSaved = true;         
    
        }
    catch (IOException e) {
            e.printStackTrace();
    }
    
    } // End of saveDatabase
    

    And used (to read) ...

    static void loadDatabase() {
    
    try {           
            FileInputStream fis = new FileInputStream("mydb.fil");
            ObjectInputStream ois = new ObjectInputStream(fis);         
            data = (ArrayList<User>)ois.readObject();
            ois.close();            
        }       
    catch (IOException e) {
            System.out.println("***catch ERROR***");
            e.printStackTrace();
    
        }       
    catch (ClassNotFoundException e) {
            System.out.println("***catch ERROR***");
            e.printStackTrace();
        }   
    } // End of loadDatabase 
    
    0 讨论(0)
提交回复
热议问题