BIO and NIO implementation file copy

 

Trivial File Copy

 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     }

Were achieved by copying the file input and output streams, this is achieved by conventional BIO

 

NIO implementation file copy

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     }

Respectively two channels from two streams, sourceCh responsible for reading data, destCh responsible for writing data, and then call the method directly transferFrom one step to achieve a file copy.

Guess you like

Origin www.cnblogs.com/baixiaoguang/p/12055903.html