首页 > 其他 > 详细

BIO和NIO实现文件复制

时间:2019-12-17 18:36:11      阅读:110      评论:0      收藏:0      [点我收藏+]

 

普通文件复制

 1 public void copyFile() throws Exception{
 2         FileInputStream fis=new FileInputStream("C:\\Users\\zdx\\Desktop\\oracle.mov");
 3         FileOutputStream fos=new FileOutputStream("d:\\oracle.mov");
 4         byte[] b=new byte[1024]; while (true) {
 5             int res=fis.read(b);
 6             if(res==-1){
 7                 break;
 8             }
 9             fos.write(b,0,res);
10         }
11         fis.close();
12         fos.close();
13     }

分别通过输入流和输出流实现了文件的复制,这是通过传统的 BIO 实现的

 

NIO实现文件复制

1  public void copyFile() throws Exception{
2         FileInputStream fis=new FileInputStream("d:\\test.wmv");
3         FileOutputStream fos=new FileOutputStream("d:\\test\\test.wmv");
4         FileChannel sourceCh = fis.getChannel();
5         FileChannel destCh = fos.getChannel();
6         destCh.transferFrom(sourceCh, 0, sourceCh.size()); sourceCh.close();
7         destCh.close();
8     }

分别从两个流中得到两个通道,sourceCh 负责读数据,destCh 负责写数据,然 后直接调用 transferFrom 方法一步到位实现了文件复制。

BIO和NIO实现文件复制

原文:https://www.cnblogs.com/baixiaoguang/p/12055903.html

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