NIO 读取中文文档,不是乱码

简单的 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();
			}
		}
	}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值