我有以下代码:阅读与FileChannel的ASCII文件和ByteArray对象
String inputFile = "somefile.txt";
FileInputStream in = new FileInputStream(inputFile);
FileChannel ch = in.getChannel();
ByteBuffer buf = ByteBuffer.allocateDirect(BUFSIZE); // BUFSIZE = 256
/* read the file into a buffer, 256 bytes at a time */
int rd;
while ((rd = ch.read(buf)) != -1) {
buf.rewind();
for (int i = 0; i < rd/2; i++) {
/* print each character */
System.out.print(buf.getChar());
}
buf.clear();
}
但字符获取在显示的。这是否与使用Unicode字符的Java有关?我该如何纠正?
我有大量的数据,我正在尝试优化阅读时间。参考:http://nadeausoftware.com/articles/2008/02/java_tip_how_read_files_quickly – Jake 2008-09-18 15:23:37
@Jake,在你的例子中你读取字节,然后解码为字符。为什么你认为这比使用BufferedReader更快?你指出的有趣的基准不读字符。 – 2010-03-16 20:49:28