我一直在使用下面的成语一段时间了.它似乎是最广泛的,至少在我访问过的网站上.
是否有更好/不同的方式将文件读入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();
}
}
Run Code Online (Sandbox Code Playgroud) 最近,我对这个答案发表了评论,java.io如果我想使用“纯NIO” ,我应该远离它。
这是简化的代码(复制文件):
private static void copy(File source, File destination) throws IOException {
long length = source.length();
FileChannel input = new FileInputStream(source).getChannel();
FileChannel output = new FileOutputStream(destination).getChannel();
input.transferTo(0, length, output);
output.close();
input.close();
}
Run Code Online (Sandbox Code Playgroud)
(代码极其简化:最终尝试删除并循环执行)
我的问题是如何在FileChannel不使用java.io(FileInputStream)的情况下获取一个或其他NIO类来读取文件?
编辑:
Java 6(或之前)