首页 > 编程语言 > 详细

Java NIO 之 复制文件 案例

时间:2017-09-25 18:35:53      阅读:273      评论:0      收藏:0      [点我收藏+]


需求:实现文件的copy


练习目的:

  1.  了解JavaNIO知识,主要是关注一下FileInputStream,FileChannel,FileOutputStream,ByteBuffer 之间的关系

  2. 了解如何获取FileChannel

public class CopyFile {
    public static void main(String[] args) throws Exception {
        String inFile = "gitHub.txt";
        String outFile = "gitHub2.txt";
        
        //获取源文件和目标文件的输入流、输出流
        FileInputStream fin = new FileInputStream(inFile);
        FileOutputStream fout = new FileOutputStream(outFile);
        
        //获取输入、输出通道
        FileChannel fcin = fin.getChannel();
        FileChannel fcout = fout.getChannel();
        
        //创建缓存区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        
        while (true) {
        
            //清楚缓存区的数据,可以接收新的数据
            buffer.clear();
        
            //从输入通道中将数据读到缓冲区
            int r = fcin.read(buffer);
        
            //read方法返回读取的字节数,可能为0, 如果该通道已经达到流的末尾,则返回-1
            if (r == -1) {
                break;
            }
        
            //flip方法,让缓冲区可以将新读入的数据写入另一个通道
            buffer.flip();
        
            //从缓存区 将数据写到 输出通道里
            fcout.write(buffer);
        }
        
        //最后关闭
        fcin.close();
        fout.close();
    }
}


总结如下:

  1. 数据的流向:

   技术分享

  1. 什么时候调用FileChannel的read,write方法?

   根据数据的方向来确定

   技术分享  







   

   







本文出自 “XEJ分布式工作室” 博客,请务必保留此出处http://xingej.blog.51cto.com/7912529/1968417

Java NIO 之 复制文件 案例

原文:http://xingej.blog.51cto.com/7912529/1968417

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