Java加速读取复制超大文件
时间:2021-05-11 08:51:27|栏目: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) + "毫秒");
}
/**
* 使用文件通道的方式复制文件
* @param source 源文件
* @param target 目标文件
*/
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();
}
}
}
/**
* 普通缓冲复制
* @param source 源文件
* @param target 目标文件
*/
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();
}
}
}
}
}
上一篇:Spring Boot利用Lombok减少Java中样板代码的方法示例
栏 目:JAVA代码
本文标题:Java加速读取复制超大文件
本文地址:http://www.codeinn.net/misctech/118862.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




