Khalid
Khalid

Reputation: 303

How to populate an ArrayList with text from an input file?

I saved some of my ArrayList's to a file and it has following format:

[hotel1, hotel2, hotel3]               // ArrayList 1 contents
[hotel5, hotel6]                       // ArrayList 2 contents

When I am reading, I want to assign for example an ArrayList myList, and I want to add hotel1, hotel2 and hotel3 to myList. Any way I can do that directly? Currently I have a string value that reads next line, it saves brackets. Was looking for another way, so that I can assign each line to an ArrayList < String > object.

public class MyClass1 {
   ArrayList<String> myList = new ArrayList<String>();
    ... // some other code

private void loadUp() throws IOException{
    JFileChooser chooser = new JFileChooser();
        chooser.setDialogTitle("Choose a file to open...");
        checker = chooser.showOpenDialog(null);

    // if open is clicked
    if (checker == JFileChooser.APPROVE_OPTION) {
        File inFile = chooser.getSelectedFile();
        Scanner in = new Scanner(inFile);
        while (in.hasNextLine()) {
            // Here want to assign next line to myList
        }
        in.close();
}
 }

Upvotes: 0

Views: 2269

Answers (2)

M Sach
M Sach

Reputation: 34424

Try below code to read each line

 BufferedReader br = new BufferedReader(new FileReader(file));
    String line;
    while ((line = br.readLine()) != null) {
       // process the line.
    }
    br.close();

Upvotes: 2

gparyani
gparyani

Reputation: 1988

Use this:

Scanner file = new Scanner(myFile);
ArrayList<Scanner> lines = new ArrayList<>();
while(file.hasNextLine())
    lines.add(new Scanner(file.nextLine()));
ArrayList<ArrayList<String>> lists = new ArrayList<>(lines.size());
for(Scanner s : lines)
    s.useDelimeter("[, ]" + System.lineSeparator());
for(int i = 0; i < lines.size(); ++i)
{
    while(lines.get(i).hasNext())
    {
        lists.add(new ArrayList<String>());
        lists.get(i).add(lines.get(i).next());
    }
}

Then you'll end up with a list of lists of strings that contain the values.

Upvotes: 3

Related Questions