Search code examples
javaarraylistfile-handlingreadfile

How to read from files and store it in ArrayList of objects?


This is my save method

public static void save() {
        try {
            PrintWriter myWriter = new PrintWriter("database.txt");
            for(int i=0; i<people.size(); i++) {
                myWriter.println(people.get(i).toString());
            }
            myWriter.close();
            System.out.println("Successfully wrote to the file.");
            menu();
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }

This is what it looks like in the file

    Donald     Trump  23323.00

This is the fields and the name of the arraylist

ArrayList<Person> people = new ArrayList<Person>();
public Person(String name, String password, double money) {
        this.name = name;
        this.password = password;
        this.money = money;
    }
constructors below.....

How do i read that file and store it in the arraylist of objects? Need help :D


Solution

  • Read the file line by line and use same delimiter you have used in toString of Person class.

    Like: let se you have used " " as delimiter.

    then read line by line and split the data using that delimiter and convert the data respectively

    String line = reader.readLine();
    String[] array = line.split(" ")// use same delimiter used to write
    if(array.lenght() ==3){ // to check if data has all three parameter 
        people.add(new Person(array[0], array[1], Double.parseDouble(array[2]))); 
        // you have to handle case if Double.parseDouble(array[2]) throws exception
    }