我有一个大约4MB的文件,该文件是一个只包含普通键盘字符的ASCII文件。我尝试了java.io包中的许多类来将文件内容读取为字符串。如果逐个字符地进行读取(使用FileReader和BufferedReader),需要大约40秒钟;而使用java.nio包(FileChannel和ByteBuffer)读取内容需要大约25秒钟。据我所知,这需要略微较长的时间。是否有人知道任何可以将此时间消耗减少到约10秒左右的方法?甚至像创建C语言文件读取器并从java中调用这样的解决方案也可以。我使用以下代码片段在22秒内读取了这个4MB的文件 -
public static String getContents(File file) {
try {
if (!file.exists() && !file.isFile()) {
return null;
}
FileInputStream in = new FileInputStream(file);
FileChannel ch = in.getChannel();
ByteBuffer buf = ByteBuffer.allocateDirect(512);
Charset cs = Charset.forName("ASCII");
StringBuilder sb = new StringBuilder();
int rd;
while ((rd = ch.read(buf)) != -1) {
buf.rewind();
CharBuffer chbuf = cs.decode(buf);
for (int i = 0; i < chbuf.length(); i++) {
sb.append(chbuf.get());
}
buf.clear();
}
String contents = sb.toString();
System.out.println("File Contents:\n"+contents);
return contents;
} catch (Exception exception) {
System.out.println("Error:\n" + exception.getMessage());
return null;
}
}