BIO和NIO实现文件复制

 

普通文件复制

复制代码
 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 方法一步到位实现了文件复制。

转载:https://www.cnblogs.com/baixiaoguang/p/12055903.html
posted @ 2020-08-01 10:24  KyleBro  阅读(158)  评论(0编辑  收藏  举报