Java将文件读入ArrayList?

78

如何在Java中将文件内容读入ArrayList<String>中?

这里是文件内容:

cat
house
dog
.
.
.
13个回答

137

这段 Java 代码读取每个单词并将其放入 ArrayList 中:

Scanner s = new Scanner(new File("filepath"));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()){
    list.add(s.next());
}
s.close();

如果您想逐行读取而不是逐个单词读取,请使用 s.hasNextLine()s.nextLine()


4
哦,使用ScannerBufferedReader更简短,且无需处理任何异常。我想在Java 5之前,没有Scanner时我习惯使用BufferedReader,尽管我已经使用Java 5和6很多年了。当然,如果有可用的Commons IO库,就像其他人提到的那样,它会提供最短的答案,所以现在我通常都使用它。 - WhiteFang34
9
你需要指定scanner的分隔符吗?因为默认的分隔符是空格符。也就是说,应该这样写:new Scanner(new File("filepath")).useDelimiter("\n"); - Hedley
@Hedley 对于 new Scanner(new File("filepath")).useDelimiter(System.lineSeparator()),建议使用 java7,因为它在不同的操作系统上可能会有所不同。 - Tschallacka

62

您可以使用:

List<String> list = Files.readAllLines(new File("input.txt").toPath(), Charset.defaultCharset() );

来源: Java API 7.0


5
我会在此处使用特定的字符集,而不是依赖于当前平台的字符集。 - Stephan
8
你可以使用Paths.get("input.txt")代替new File("input.txt").toPath()。 - assylias

50

使用commons-io的一行代码:

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

guava一样:

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

5
为什么不使用Charsets.UTF_8而是使用forName - Fluffy

31

我发现最简单的形式是...

List<String> lines = Files.readAllLines(Paths.get("/path/to/file.txt"));

11

Java 8中,您可以使用流和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);
}

或者作为包括从文件系统加载文件的函数:

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;
}

1
List<String> lines = Files.lines(Paths.get("./input.txt")).collect(Collectors.toList()); - user6186835

6
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();

为什么我无法使用“line.size()”找到ArrayList的大小? - user618712

2

例如,您可以以以下方式完成此操作(带有异常处理的完整代码):

BufferedReader in = null;
List<String> myList = new ArrayList<String>();
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();
    }
}

2
在Java 7+中,您可以使用try-with-resources。 - Afshin Moazami

1
//CS124 HW6 Wikipedia Relation Extraction
//Alan Joyce (ajoyce)
public List<String> addWives(String fileName) {
    List<String> wives = new ArrayList<String>();
    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;
}

1

分享一些分析信息。通过一个简单的测试来看读取大约1180行数值需要多长时间。

如果需要快速读取数据,请使用经典的BufferedReader FileReader示例。它只花费了我约8毫秒。

Scanner要慢得多。花费了我约138毫秒。

Java 8中不错的Files.lines(...)是最慢的版本。花费了我约388毫秒。


1

这是一个对我非常有效的解决方案:

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]+")
);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接