简单的 NIO 读文本方法,读取英文文档是没问题的,可是读取中文文档会出现乱码。
从网上找到一种取中文文档不是乱码的 NIO 读 的写法:
// NIO 读取中文文档
public static void readChn() {
FileOutputStream fos = null;
FileInputStream fis = null;
FileChannel fcIn = null;
FileChannel fcOut = null;
try {
// 读取的中文文档
File file = new File( "c://NIO.txt" );
// 输出文档
File backupFile = new File( "c://writeOut.txt" );
backupFile.createNewFile();
fis = new FileInputStream( file );
fos = new FileOutputStream( backupFile );
// 获取输入通道
fcIn = fis.getChannel();
// 获取输出通道
fcOut = fos.getChannel();
// 创建缓冲区
ByteBuffer byteBuffer = ByteBuffer.allocate( 102400 ); // 这里用 1 或者 一个很大的数 比如 1024。比较小的数也是有几率出现乱码的
CharBuffer charBuffer = CharBuffer.allocate( 102400 );
char[] charCache = null;
// 字符编码
Charset charset = Charset.forName( "GBK" );
CharsetDecoder charDecoder = charset.newDecoder();
// 读取数据到缓冲区
while ( ( fcIn.read( byteBuffer ) ) != -1 ) {
byteBuffer.flip();
charDecoder.decode( byteBuffer, charBuffer, true );
charBuffer.flip();
charCache = new char[ charBuffer.length() ];
while ( charBuffer.hasRemaining() ) {
charBuffer.get( charCache );
String str = new String( charCache );
byteBuffer = ByteBuffer.wrap( str.getBytes() );
System.out.println( str );
}
fcOut.write( byteBuffer );
charBuffer.clear();
byteBuffer.clear();
}
} catch ( FileNotFoundException e ) {
e.printStackTrace();
} catch ( IOException e ) {
e.printStackTrace();
} finally {
try {
if ( fis != null ) {
fis.close();
}
} catch ( IOException e ) {
e.printStackTrace();
}
try {
if ( fos != null ) {
fos.close();
}
} catch ( IOException e ) {
e.printStackTrace();
}
try {
if ( fcIn != null ) {
fcIn.close();
}
} catch ( IOException e ) {
e.printStackTrace();
}
try {
if ( fcOut != null ) {
fcOut.close();
}
} catch ( IOException e ) {
e.printStackTrace();
}
}
}