Java reading a file into an ArrayList?

后端 未结 13 989
醉话见心
醉话见心 2020-11-22 12:05

How do you read the contents of a file into an ArrayList in Java?

Here are the file contents:

cat
ho         


        
相关标签:
13条回答
  • 2020-11-22 13:03

    This Java code reads in each word and puts it into the ArrayList:

    Scanner s = new Scanner(new File("filepath"));
    ArrayList<String> list = new ArrayList<String>();
    while (s.hasNext()){
        list.add(s.next());
    }
    s.close();
    

    Use s.hasNextLine() and s.nextLine() if you want to read in line by line instead of word by word.

    0 讨论(0)
提交回复
热议问题