如何在Java中将文件内容读入ArrayList<String>
中?
这里是文件内容:
cat
house
dog
.
.
.
这段 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()
。
您可以使用:
List<String> list = Files.readAllLines(new File("input.txt").toPath(), Charset.defaultCharset() );
来源: Java API 7.0
Paths.get("input.txt")
д»Јж›їnew File("input.txt").toPath()
гЂ‚ - assylias使用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"));
Charsets.UTF_8
而是使用forName
? - Fluffy我发现最简单的形式是...
List<String> lines = Files.readAllLines(Paths.get("/path/to/file.txt"));
在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;
}
List<String> lines = Files.lines(Paths.get("./input.txt")).collect(Collectors.toList());
- user6186835List<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();
例如,您可以以以下方式完成此操作(带有异常处理的完整代码):
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();
}
}
//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;
}
分享一些分析信息。通过一个简单的测试来看读取大约1180行数值需要多长时间。
如果需要快速读取数据,请使用经典的BufferedReader FileReader示例。它只花费了我约8毫秒。
Scanner要慢得多。花费了我约138毫秒。
Java 8中不错的Files.lines(...)是最慢的版本。花费了我约388毫秒。
这是一个对我非常有效的解决方案:
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]+")
);
Scanner
比BufferedReader
更简短,且无需处理任何异常。我想在Java 5之前,没有Scanner
时我习惯使用BufferedReader
,尽管我已经使用Java 5和6很多年了。当然,如果有可用的Commons IO库,就像其他人提到的那样,它会提供最短的答案,所以现在我通常都使用它。 - WhiteFang34new Scanner(new File("filepath")).useDelimiter(System.lineSeparator())
,建议使用 java7,因为它在不同的操作系统上可能会有所不同。 - Tschallacka