我已经用下面这个成语有一段时间了。这似乎是传播最广的,至少在我访问过的网站上。
在Java中有没有更好/不同的方法将文件读入字符串?
private String readFile(String file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader (file));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
try {
while((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
return stringBuilder.toString();
} finally {
reader.close();
}
}
该代码将规范换行符,这可能是您真正想要做的,也可能不是。
这里有一个替代方案,它没有做到这一点,而且比NIO代码更容易理解(IMO)(尽管它仍然使用java.NIO.charset.charset):
public static String readFile(String file, String csName)
throws IOException {
Charset cs = Charset.forName(csName);
return readFile(file, cs);
}
public static String readFile(String file, Charset cs)
throws IOException {
// No real need to close the BufferedReader/InputStreamReader
// as they're only wrapping the stream
FileInputStream stream = new FileInputStream(file);
try {
Reader reader = new BufferedReader(new InputStreamReader(stream, cs));
StringBuilder builder = new StringBuilder();
char[] buffer = new char[8192];
int read;
while ((read = reader.read(buffer, 0, buffer.length)) > 0) {
builder.append(buffer, 0, read);
}
return builder.toString();
} finally {
// Potential issue here: if this throws an IOException,
// it will mask any others. Normally I'd use a utility
// method which would log exceptions and swallow them
stream.close();
}
}
如果您需要字符串处理(并行处理),Java8有很棒的StreamAPI。
String result = Files.lines(Paths.get("file.txt"))
.parallel() // for parallel processing
.map(String::trim) // to change line
.filter(line -> line.length() > 2) // to filter some lines by a predicate
.collect(Collectors.joining()); // to join lines
JDK示例samples/lambda/BulkDataOperations中提供了更多示例,可以从Oracle Java SE 8下载页面下载
另一个单线示例
String out = String.join("\n", Files.readAllLines(Paths.get("file.txt")));