我有以下代码:
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(); } } }