通过fileChannel复制文件

来源:互联网 发布:江苏泰微课网络课程 编辑:程序博客网 时间:2024/05/22 01:57

  

 

传统的文件复制都是利用 缓冲输入输出流来完成

 

最近在网上发现了一个更加高效简单的方法:利用FileChannel.

 

先再写次传统的方法:

 

public void bufferedFileCopy(File src, File dest) {InputStream fis = null;OutputStream fos = null;try {fis = new BufferedInputStream(new FileInputStream(src));fos = new BufferedOutputStream(new FileOutputStream(dest));byte[] buffer = new byte[2048];int len;while ((len = fis.read(buffer)) != -1) {fos.write(buffer, 0, len);}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {try {fis.close();fos.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}


 

利用FileChannel的高效简单方法:

 

public void channelFileCopy(File src, File dest) {FileInputStream fis = null;FileOutputStream fos = null;FileChannel in = null;FileChannel out = null;try {fis = new FileInputStream(src);fos = new FileOutputStream(dest);in = fis.getChannel();out = fos.getChannel();in.transferTo(0, in.size(), out);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {try {fis.close();in.close();fos.close();out.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

只需一句关键就完成文件复制功能:

in.transferTo(0, in.size(), out);


再来看看耗时情况:

File src = new File(mFileHelper.SDCardPath() + "/1.zip");File dest = new File(mFileHelper.SDCardPath()+ "/kingzhengTourGuide/videos/1.zip");/** * 先看看传统方法耗时 */long start = System.currentTimeMillis();mFileHelper.bufferedFileCopy(src, dest);long end = System.currentTimeMillis();System.out.println("利用buffered复制,用时: " + (end - start) + "ms");

 

/** * 再看看FileChannel耗时 */start = System.currentTimeMillis();mFileHelper.channelFileCopy(src, dest);end = System.currentTimeMillis();System.out.println("利用FileChannel复制,用时: " + (end - start)+ "ms");


 

 

 

有点奇怪 竟然耗时还多了...在测试其他文件的时候 使用FileChannel 会少将近 三分之一;

 

有兴趣的同学可以自己试试~~

0 0
原创粉丝点击