Java reading a file into an ArrayList?

2019-01-01 13:11发布

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

Here are the file contents:

cat
house
dog
.
.
.

Just read each word into the ArrayList.

标签: java
12条回答
临风纵饮
2楼-- · 2019-01-01 14:00

Simplest form I ever found is...

List<String> lines = Files.readAllLines(Paths.get("/path/to/file.txt"));
查看更多
梦该遗忘
3楼-- · 2019-01-01 14:05
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();
查看更多
大哥的爱人
4楼-- · 2019-01-01 14:06

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

查看更多
几人难应
5楼-- · 2019-01-01 14:11

In Java 8 you could use streams and Files.lines:

List<String> list = null;
try (Stream<String> lines = Files.lines(myPathToTheFile))) {
    list = lines.collect(Collectors.toList());
} catch (IOException e) {
    LOGGER.error("Failed to load file.", e);
}

Or as a function including loading the file from the file system:

private List<String> loadFile() {
    List<String> list = null;
    URI uri = null;

    try {
        uri = ClassLoader.getSystemResource("example.txt").toURI();
    } catch (URISyntaxException e) {
        LOGGER.error("Failed to load file.", e);
    }

    try (Stream<String> lines = Files.lines(Paths.get(uri))) {
        list = lines.collect(Collectors.toList());
    } catch (IOException e) {
        LOGGER.error("Failed to load file.", e);
    }
    return list;
}
查看更多
余生无你
6楼-- · 2019-01-01 14:12

Here is an entire program example:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class X {
    public static void main(String[] args) {
    File f = new File("D:/projects/eric/eclipseworkspace/testing2/usernames.txt");
        try{
            ArrayList<String> lines = get_arraylist_from_file(f);
            for(int x = 0; x < lines.size(); x++){
                System.out.println(lines.get(x));
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
        System.out.println("done");

    }
    public static ArrayList<String> get_arraylist_from_file(File f) 
        throws FileNotFoundException {
        Scanner s;
        ArrayList<String> list = new ArrayList<String>();
        s = new Scanner(f);
        while (s.hasNext()) {
            list.add(s.next());
        }
        s.close();
        return list;
    }
}
查看更多
怪性笑人.
7楼-- · 2019-01-01 14:14

To share some analysis info. With a simple test how long it takes to read ~1180 lines of values.

If you need to read the data very fast, use the good old BufferedReader FileReader example. It took me ~8ms

The Scanner is much slower. Took me ~138ms

The nice Java 8 Files.lines(...) is the slowest version. Took me ~388ms.

查看更多
登录 后发表回答