解决nio中文乱码问题
public class TestChannel {
public static void main(String[] args) throws Exception {
charChannel();
}
public static void charChannel() throws Exception {
RandomAccessFile raf = new RandomAccessFile("C:\\Users\\Documents\\新建文本文档.txt", "r");
FileChannel channel = raf.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(64);
CharBuffer charBuffer = CharBuffer.allocate(64);
CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
long offSet = 0;
while (channel.read(byteBuffer, offSet) != -1) {
byteBuffer.flip();
decoder.decode(byteBuffer, charBuffer, false);
charBuffer.flip();
char[] chars = new char[charBuffer.remaining()];
while (charBuffer.hasRemaining()) {
charBuffer.get(chars);
System.out.print(new String(chars));
}
int position = byteBuffer.position();
offSet += position;
byteBuffer.clear();
charBuffer.clear();
}
}
}