work hard work smart

专注于Java后端开发。 不断总结,举一反三。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Java NIO 文件通道使用

Posted on 2019-08-11 22:20  work hard work smart  阅读(133)  评论(0编辑  收藏  举报

读取一个文件的内容,然后写入另外一个文件

public class NioTest4 {

    public static void main(String[] args) throws  Exception {
        FileInputStream inputStream = new FileInputStream("input.txt");

        FileOutputStream outputStream = new FileOutputStream("output.txt");

        FileChannel inputChannel = inputStream.getChannel();
        FileChannel outputChannel = outputStream.getChannel();

        ByteBuffer buffer =  ByteBuffer.allocate(1024);
        while (true){
            buffer.clear();
            int read = inputChannel.read(buffer);
            if( -1 == read){
                break;
            }
            buffer.flip();

            outputChannel.write(buffer);

        }
        inputChannel.close();
        outputChannel.close();

    }

}

  通过NIO读取文件涉及3个步骤

1、从FileInputStream获取FileChannel对象

2、创建Buffer

3、将数据从Channel读取到Buffer中

 

    绝对方法与相对方法的含义

1、相对方法: limit值与position值会在操作时被考虑到

2、绝对方法: 完全忽略调limit值和position值。