javanio读取文件超出问题

当使用Java NIO读取文件时,出现读取内容超出文件实际内容的现象。例如,读取名为a.txt的文件,其内容为'12345 12345 123',但输出结果却是'12345 12345 12312345 '。问题源于在调用byteBuffer.clear()或byteBuffer.compact()时,仅重置了状态标识字段,而未初始化byte数组。解决方案是确保正确管理缓冲区的状态。
摘要由CSDN通过智能技术生成

问题:读取一个文件按读取的byte[]输出时输出超出文件内容

问题发生示例: 有文件a.txt,内容为 ‘12345 \n 12345 \n 123’,通过如下代码输出结果为’12345 \n 12345 \n 12312345\n’ 即表现形式是输出超了

public class Demo1 {
    public static void main(String[] args) throws IOException {
        File f = new File("filePath");
        FileInputStream fis = new FileInputStream(f);
        FileChannel channel = fis.getChannel();
        ByteBuffer allocate = ByteBuffer.allocate(1024);
        int i = -1;
        while ((i = channel.read(allocate)) != -1) {
            allocate.flip();
            byte[] array = allocate.array();
            System.out.println(new String(array));
            allocate.clear();
        }
        channel.close();
//        fis.close();
    }
}

原因:调用byteBuffer.cl

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 Java NIO 读取文件需要以下步骤: 1. 创建一个文件通道(FileChannel)对象,通过 FileInputStream 的 getChannel() 方法获取。 2. 创建一个字节缓冲区(ByteBuffer)对象,用于存放从文件中读取的数据。 3. 调用通道的 read() 方法,将数据从文件读取到缓冲区中。 4. 循环读取数据,直到文件末尾。 5. 关闭文件通道和文件输入流。 下面是一个示例代码,演示如何使用 Java NIO 读取文件: ```java import java.io.FileInputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class NIOFileReader { public static void main(String[] args) throws Exception { FileInputStream inputStream = new FileInputStream("filename.txt"); FileChannel channel = inputStream.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (channel.read(buffer) != -1) { buffer.flip(); // 切换读模式 while (buffer.hasRemaining()) { System.out.print((char) buffer.get()); // 读取数据 } buffer.clear(); // 切换写模式 } channel.close(); inputStream.close(); } } ``` 在上面的代码中,我们首先创建了一个文件输入流(FileInputStream)对象,并通过 getChannel() 方法获取了一个文件通道(FileChannel)对象。然后我们创建了一个字节缓冲区(ByteBuffer)对象,并指定了缓冲区的大小为 1024 字节。接下来,我们使用 while 循环读取数据,每次读取一部分数据到缓冲区中,然后切换读模式,读取数据,再切换写模式,清空缓冲区。最后,我们关闭了文件通道和文件输入流。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值