Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading text file into arraylist

Tags:

java

arraylist

I really new to Java so I'm having some trouble figuring this out. So basically I have a text file that looks like this:

1:John:false  
2:Bob:false    
3:Audrey:false

How can I create an ArrayList from the text file for each line?

like image 232
Audrey Avatar asked Dec 11 '22 17:12

Audrey


2 Answers

Read from a file and add each line into arrayList. See the code for example.

public static void main(String[] args) {

        ArrayList<String> arr = new ArrayList<String>();
        try (BufferedReader br = new BufferedReader(new FileReader(<your_file_path>)))
        {

            String sCurrentLine;

            while ((sCurrentLine = br.readLine()) != null) {
                arr.add(sCurrentLine);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } 

    }
like image 96
Priyansh Goel Avatar answered Dec 13 '22 07:12

Priyansh Goel


While the answer above me works, here's another way to do it. Make sure to import java.util.Scanner.

public static void main(String[] args) {
     ArrayList<String> list = new ArrayList<String>();
     Scanner scan = new Scanner("YOURFILE.txt");
     while(scan.hasNextLine()){
         list.add(scan.nextLine());
     }
     scan.close();
}
like image 29
Danny0317 Avatar answered Dec 13 '22 06:12

Danny0317