当前位置: 移动技术网 > IT编程>开发语言>Java > Java加速读取复制超大文件

Java加速读取复制超大文件

2019年07月19日  | 移动技术网IT编程  | 我要评论

用文件通道(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();
}
}
}
 }

 }

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网