美文网首页
10.NIO读文件和写文件

10.NIO读文件和写文件

作者: 未知的证明 | 来源:发表于2019-03-02 12:20 被阅读0次

本文介绍了如何用NIO读取文件input.txt和写文件output.txt,并说明,如果 不用clear()产生后果的原因

1.新建一个文件input.txt,如下图

新建的input文件

2.具体代码实现

package com.liyuanfeng.nio;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NioTest4 {
    public static void main(String[] args) throws Exception {
        FileInputStream fileInputStream = new FileInputStream("input.txt");
        FileOutputStream fileOutputStream  = new FileOutputStream("output.txt");
        FileChannel fileInputStreamChannel = fileInputStream.getChannel();
        FileChannel fileOutputStreamChannel = fileOutputStream.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (true){
            buffer.clear();//将postion置0,limit变成capacity,迎接下一次读取
            int read = fileInputStreamChannel.read(buffer);//将字节读到buffer里,返回所读字节,如果为-1,则表示读到文件的结尾了
            if (-1== read) break;//如果read为-1,跳出循环
            buffer.flip();//反转,将buffer写出到通道中,持久化到硬盘中
            fileOutputStreamChannel.write(buffer);
        }
    }
}

3.假如将buffer.clear注释掉,会发生如下现象:

一直讲读取的数据一直写到output.txt里,并且出现死循环

4.解释一下3标题出现的原因:

  1. 如果删掉buffer.clear();则读完之后,position和limit处于同一个位置,就是读到buffer的最后的地方。
  2. 这时候执行int read = fileInputStreamChannel.read(buffer);因为potion和limit一样,所以read值为0,读3 不到任何数据;
  3. int read = fileInputStreamChannel.read(buffer);永远不会出现为-1的情况,所以不可能跳出循环,会一直死循环;
  4. buffer.flip();反转,将buffer写出到通道中,持久化到硬盘中,flip()会将potion置为0,limit不变,继续向输出通道中写数据。
  5. 所以会一直死循环,一直写数据。

相关文章

网友评论

      本文标题:10.NIO读文件和写文件

      本文链接:https://www.haomeiwen.com/subject/wnjeuqtx.html