Java reading a file into an ArrayList?

后端 未结 13 1009
醉话见心
醉话见心 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:56

    You can for example do this in this way (full code with exceptions handlig):

    BufferedReader in = null;
    List myList = new ArrayList();
    try {   
        in = new BufferedReader(new FileReader("myfile.txt"));
        String str;
        while ((str = in.readLine()) != null) {
            myList.add(str);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            in.close();
        }
    }
    

提交回复
热议问题