Java reading a file into an ArrayList?

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

    Add this code to sort the data in text file. Collections.sort(list);

    0 讨论(0)
  • Simplest form I ever found is...

    List<String> lines = Files.readAllLines(Paths.get("/path/to/file.txt"));
    
    0 讨论(0)
  • 2020-11-22 12:43
        Scanner scr = new Scanner(new File(filePathInString));
    /*Above line for scanning data from file*/
    
        enter code here
    
    ArrayList<DataType> list = new ArrayList<DateType>();
    /*this is a object of arraylist which in data will store after scan*/
    
    while (scr.hasNext()){
    

    list.add(scr.next()); } /*above code is responsible for adding data in arraylist with the help of add function */

    0 讨论(0)
  • 2020-11-22 12:46

    A one-liner with commons-io:

    List<String> lines = FileUtils.readLines(new File("/path/to/file.txt"), "utf-8");
    

    The same with guava:

    List<String> lines = 
         Files.readLines(new File("/path/to/file.txt"), Charset.forName("utf-8"));
    
    0 讨论(0)
  • 2020-11-22 12:48
    List<String> words = new ArrayList<String>();
    BufferedReader reader = new BufferedReader(new FileReader("words.txt"));
    String line;
    while ((line = reader.readLine()) != null) {
        words.add(line);
    }
    reader.close();
    
    0 讨论(0)
  • 2020-11-22 12:50

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

    List<String> 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<String> lines = Arrays.asList(
        new Scanner(new File(file)).useDelimiter("\\Z").next().split("[\\r\\n]+")
    );
    
    0 讨论(0)
提交回复
热议问题