解决nio中文乱码问题

该博客详细介绍了如何使用Java NIO处理文件时解决中文乱码的问题。通过创建`CharsetDecoder`对象并指定UTF-8编码,配合`ByteBuffer`和`CharBuffer`进行转换,确保了从文件读取的中文字符正确显示。示例代码中展示了完整的读取过程,包括缓冲区的翻转、读取、清空等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解决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);
        //注意:读取的文件也要是UTF-8格式
        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();
        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值