使用FileChannel和ByteArrays读取ASCII文件

我有以下代码:

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有关? 我该如何纠正?

您必须知道文件的编码是什么,然后使用该编码将ByteBuffer解码为CharBuffer。 假设文件是​​ASCII:

 import java.util.*; import java.io.*; import java.nio.*; import java.nio.channels.*; import java.nio.charset.*; public class Buffer { public static void main(String args[]) throws Exception { String inputFile = "somefile"; FileInputStream in = new FileInputStream(inputFile); FileChannel ch = in.getChannel(); ByteBuffer buf = ByteBuffer.allocateDirect(BUFSIZE); // BUFSIZE = 256 Charset cs = Charset.forName("ASCII"); // Or whatever encoding you want /* read the file into a buffer, 256 bytes at a time */ int rd; while ( (rd = ch.read( buf )) != -1 ) { buf.rewind(); CharBuffer chbuf = cs.decode(buf); for ( int i = 0; i < chbuf.length(); i++ ) { /* print each character */ System.out.print(chbuf.get()); } buf.clear(); } } } 

buf.getChar()期望每个字符2个字节但你只存储1.使用:

  System.out.print((char) buf.get()); 

将print语句更改为:

 System.out.print((char)buf.get()); 

似乎有所帮助。

根据somefile.txt的编码,字符实际上可能不是由两个字节组成。 此页面提供了有关如何使用正确的编码读取流的更多信息。

糟糕的是,文件系统没有告诉你文件的编码,因为它不知道。 就它而言,它只是一堆字节。 您必须找到一些方法将编码传递给程序,以某种方式检测它,或者(如果可能)始终确保编码是相同的(例如UTF-8)。

是否有一个特殊的原因,你以你的方式阅读文件?

如果您正在读取ASCII文件,那么您应该使用Reader。

我会这样做:

 File inputFile = new File("somefile.txt"); BufferedReader reader = new BufferedReader(new FileReader(inputFile)); 

然后使用readLine或类似实际读取数据!

是的,它是Unicode。

如果您的文件中有14个字符,则只能获得7个字符?

待解决方案。 仍然在想。