首页 > 编程语言 > 详细

Java NIO 文件通道使用

时间:2019-08-12 00:03:54      阅读:114      评论:0      收藏: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值。

 

Java NIO 文件通道使用

原文:https://www.cnblogs.com/linlf03/p/11337034.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!