Java reading a file into an ArrayList?

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

    Here's a solution that has worked pretty well for me:

    List lines = Arrays.asList(
        new Scanner(new File(file)).useDelimiter("\\Z").next().split("\\r?\\n")
    );
    

    If you don't want empty lines, you can also do:

    List lines = Arrays.asList(
        new Scanner(new File(file)).useDelimiter("\\Z").next().split("[\\r\\n]+")
    );
    

提交回复
热议问题