Java将文件读入ArrayList?

use*_*712 60 java

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

这是文件内容:

cat
house
dog
.
.
.
Run Code Online (Sandbox Code Playgroud)

只需阅读每个单词ArrayList.

Ahm*_*otb 112

这个java代码读入每个单词并将其放入ArrayList:

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

使用s.hasNextLine()并且s.nextLine()如果您想逐行而不是逐字阅读.

  • 您是否需要为扫描程序指定分隔符,因为默认分隔符与空格匹配?即new Scanner(新文件("filepath")).useDelimiter("\n"); (7认同)
  • 哦,很好,使用`Scanner`比`BufferedReader`更短,没有例外可以处理.我想我习惯在Java 5之前使用`BufferedReader`当`Scanner`不存在时,尽管我多年来一直在使用Java 5和6.Commons IO库当然提供了最短的答案,如果有其他人提到的那样,所以我现在通常使用它. (4认同)

Boz*_*zho 50

commons-io的单行:

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

番石榴一样:

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

  • 为什么不使用`Charsets.UTF_8`而不是`forName`? (4认同)

Ger*_*sio 49

您可以使用:

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

来源:Java API 7.0

  • 我会在这里使用特定的Charset,而不是依赖于当前的Charset平台. (4认同)
  • 你也可以使用`Paths.get("input.txt")`而不是`new File("input.txt").toPath(0` (4认同)

Kha*_*han 15

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

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


Kri*_*ris 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);
}
Run Code Online (Sandbox Code Playgroud)

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

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;
}
Run Code Online (Sandbox Code Playgroud)


Whi*_*g34 5

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();
Run Code Online (Sandbox Code Playgroud)