My favorite way to read a small file is to use a BufferedReader and a StringBuilder.
(我最喜欢的读取小文件的方法是使用BufferedReader和StringBuilder。)
It is very simple and to the point (though not particularly effective, but good enough for most cases): (这很简单并且很关键(尽管不是特别有效,但是对于大多数情况来说已经足够了):)
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
Some has pointed out that after Java 7 you should use try-with-resources (ie auto close) features:
(有人指出,在Java 7之后,您应该使用try-with-resources (即自动关闭)功能:)
try(BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
}
When I read strings like this, I usually want to do some string handling per line anyways, so then I go for this implementation.
(当我读取这样的字符串时,无论如何我通常还是想对每行进行一些字符串处理,因此我继续进行此实现。)
Though if I want to actually just read a file into a String, I always use Apache Commons IO with the class IOUtils.toString() method.
(尽管实际上我只是想将文件读入字符串,但我始终将Apache Commons IO与IOUtils.toString()方法一起使用。)
You can have a look at the source here: (您可以在这里查看源代码:)
http://www.docjar.com/html/api/org/apache/commons/io/IOUtils.java.html
(http://www.docjar.com/html/api/org/apache/commons/io/IOUtils.java.html)
FileInputStream inputStream = new FileInputStream("foo.txt");
try {
String everything = IOUtils.toString(inputStream);
} finally {
inputStream.close();
}
And even simpler with Java 7:
(使用Java 7甚至更简单:)
try(FileInputStream inputStream = new FileInputStream("foo.txt")) {
String everything = IOUtils.toString(inputStream);
// do something with everything string
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…