How to read from a .txt file into an array of objects

I have the following sample data in a .txt file

111, Sybil, 21
112, Edith, 22
113, Mathew, 30
114, Mary, 25

the required output is

[{"number":"111","name":"Sybil","age":"21" },
{"number":"112","name":"Edith","age":"22"},
{"number":"113","name":"Mathew","age":"30"},
"number":"114","name":"Mary","age":"25"]

Sadly, I have not gone far because I cant seem to get the values out of each line. instead, this is what is displayed

[one, two, three]

    private void loadFile() throws FileNotFoundException, IOException {
        File txt = new File("Users.txt");
        try (Scanner scan = new Scanner(txt)) {
            ArrayList data = new ArrayList<>() ;
            while (scan.hasNextLine()) {
                
                data.add(scan.nextLine());
                 System.out.print(scan.nextLine()); 
            }
             System.out.print(data); 
               
            
        }

I would appreciate any help. thank you

>Solution :

Not too sure about the requirements. If you just need to know how to get the values out, then use String.split() combined with Scanner.nextLine().

Codes below:

    private void loadFile() throws FileNotFoundException, IOException {
    File txt = new File("Users.txt");
    try (Scanner scan = new Scanner(txt)) {
        ArrayList data = new ArrayList<>();
        while (scan.hasNextLine()) {
            // split the data by ", " and split at most (3-1) times
            String[] input = scan.nextLine().split(", ", 3);
            data.add(input[0]);
            data.add(input[1]);
            data.add(input[2]);

            System.out.print(scan.nextLine());
        }
        System.out.print(data);
    }
}

The output would be as below and you can further modify it yourself:

[111, Sybil, 21, 112, Edith, 22, 113, Mathew, 30, 114, Mary, 25]

However, if you need the required format as well, the closest I can get is by using a HaspMap and put it into the ArrayList.

Codes below:

    private void loadFile() throws FileNotFoundException, IOException {
    File txt = new File("Users.txt");
    try (Scanner scan = new Scanner(txt)) {
        ArrayList data = new ArrayList<>();
        while (scan.hasNextLine()) {
            // Create a hashmap to store data in correct format,
            HashMap<String, String> info = new HashMap();
            String[] input = scan.nextLine().split(", ", 3);
            info.put("number", input[0]);
            info.put("name", input[1]);
            info.put("age", input[2]);
            
            // Put it inside the ArrayList
            data.add(info);
        }
        System.out.print(data);
    }
}

And the output would be:

[{number=111, name=Sybil, age=21}, {number=112, name=Edith, age=22}, {number=113, name=Mathew, age=30}, {number=114, name=Mary, age=25}]

Hope this answer helps you well.

Leave a Reply