栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java加速读取复制超大文件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java加速读取复制超大文件

用文件通道(FileChannel)来实现文件复制,供大家参考,具体内容如下

不考虑多线程优化,单线程文件复制最快的方法是(文件越大该方法越有优势,一般比常用方法快30+%):

直接上代码:

package test;
 import java.io.BufferedInputStream;
 import java.io.BufferedOutputStream;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.nio.channels.FileChannel;

 public class Test {
public static void main(String[] args) {
File source = new File("E:\tools\fmw_12.1.3.0.0_wls.jar");
File target = new File("E:\tools\fmw_12.1.3.0.0_wls-copy.jar");
long start, end;

start = System.currentTimeMillis();
fileChannelCopy(source, target);
end = System.currentTimeMillis();
System.out.println("文件通道用时:" + (end - start) + "毫秒");

start = System.currentTimeMillis();
copy(source, target);
end = System.currentTimeMillis();
System.out.println("普通缓冲用时:" + (end - start) + "毫秒");
}


 public static void fileChannelCopy(File source, File target) {


  FileInputStream in = null;
  FileOutputStream out = null;
  FileChannel inChannel = null;
  FileChannel outChannel = null;
  try {
  in = new FileInputStream(source);
  out = new FileOutputStream(target);
  inChannel = in.getChannel();//得到对应的文件通道
  outChannel = out.getChannel();//得到对应的文件通道
  inChannel.transferTo(0, inChannel.size(), outChannel);//连接两个通道,并且从inChannel通道读取,然后写入outChannel通道
 } catch (IOException e) {
  e.printStackTrace();
  } finally {
  try {
   in.close();
   inChannel.close();
   out.close();
   outChannel.close();
  } catch (IOException e) {
   e.printStackTrace();
  }


  }


 }
 

public static void copy (File source, File target) {
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(source));
out = new BufferedOutputStream(new FileOutputStream(target));
byte[] buf = new byte[4096];
int i;
while ((i = in.read(buf)) != -1) {
out.write(buf, 0, i);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != in) {
in.close();
}
if (null != out) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
 }

 }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/138326.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号