你如何将文件的内容读入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()如果您想逐行而不是逐字阅读.
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)
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
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)
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)