Java reading a file into an ArrayList?

后端 未结 13 1150
醉话见心
醉话见心 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 12:59

    //CS124 HW6 Wikipedia Relation Extraction
    //Alan Joyce (ajoyce)
    public List addWives(String fileName) {
        List wives = new ArrayList();
        try {
            BufferedReader input = new BufferedReader(new FileReader(fileName));
            // for each line
            for(String line = input.readLine(); line != null; line = input.readLine()) {
                wives.add(line);
            }
            input.close();
        } catch(IOException e) {
            e.printStackTrace();
            System.exit(1);
            return null;
        }
        return wives;
    }
    

提交回复
热议问题