Java读取复制超大文件加速
来源:互联网 发布:蹭网软件下载 编辑:程序博客网 时间:2024/06/05 14:22
用文件通道(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();
}
}
}
}
}
- Java读取复制超大文件加速
- java读取超大文件
- java读取超大文件
- 内存映射文件-java读取超大文件
- JAVA使用多线程读取超大文件
- JAVA使用多线程读取超大文件
- Java NIO 按行读取超大文件
- php 读取超大文件
- PHP读取超大文件
- Java读取超大文本文件
- Java读取超大文本文件
- PHP读取超大日志文件
- php读取超大日志文件
- Java读取并复制文件
- java 超大文件上传
- java超大文件读写
- java IO流 读取文件 && 文件复制
- JAVA读取超大文件内容并处理写到另外文件中
- javaweb 的错误信息在tomcat的位置
- Java+Selenium3方法篇11-findElement之By CSS
- 关于ListView嵌套ListView,外层Item点击事件的冲突解决
- 浅谈类加载器
- 负载均衡算法WRR介绍
- Java读取复制超大文件加速
- SVM中的核函数
- java填充替换数组元素
- poj2774
- 利用PHPExcel导出Excel并设置Excel格式
- CodeForces #157(258A|258B|258C|258D|258E)|数位DP|搜索|线段树
- Could not connect to SMTP host: smtp.163.com, port: 25;阿里云 ECS
- Master启动的源码详解
- TCP网络编程中connect()、listen()和accept()三者之间的关系