当前位置: 移动技术网 > IT编程>开发语言>Java > java高效实现大文件拷贝功能

java高效实现大文件拷贝功能

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

多媒体计算机,上海国庆兼职,网游之异世王者

 在java中,filechannel类中有一些优化方法可以提高传输的效率,其中transferto( )和 transferfrom( )方法允许将一个通道交叉连接到另一个通道,而不需要通过一个缓冲区来传递数据。只有filechannel类有这两个方法,因此 channel-to-channel 传输中通道之一必须是 filechannel。不能在sock通道之间传输数据,不过socket 通道实现writablebytechannel 和 readablebytechannel 接口,因此文件的内容可以用 transferto( )方法传输给一个 socket 通道,或者也可以用 transferfrom( )方法将数据从一个 socket 通道直接读取到一个文件中。

channel-to-channel 传输是可以极其快速的,特别是在底层操作系统提供本地支持的时候。某些操作系统可以不必通过用户空间传递数据而进行直接的数据传输。对于大量的数据传输,这会是一个巨大的帮助。

注意:如果要拷贝的文件大于4g,则不能直接用channel-to-channel 的方法,替代的方法是使用bytebuffer,先从原文件通道读取到bytebuffer,再将bytebuffer写到目标文件通道中。

下面为实现大文件快速拷贝的代码:

import java.io.file;
import java.io.ioexception;
import java.io.randomaccessfile;
import java.nio.bytebuffer;
import java.nio.channels.filechannel;
 
public class bigfilecopy {
 
 
 /**
 * 通过channel到channel直接传输
 * @param source
 * @param dest
 * @throws ioexception
 */
 public static void copybychanneltochannel(string source, string dest) throws ioexception {
 file source_tmp_file = new file(source);
 if (!source_tmp_file.exists()) {
 return ;
 }
 randomaccessfile source_file = new randomaccessfile(source_tmp_file, "r");
 filechannel source_channel = source_file.getchannel();
 file dest_tmp_file = new file(dest);
 if (!dest_tmp_file.isfile()) {
 if (!dest_tmp_file.createnewfile()) {
 source_channel.close();
 source_file.close();
 return;
 }
 }
 randomaccessfile dest_file = new randomaccessfile(dest_tmp_file, "rw");
 filechannel dest_channel = dest_file.getchannel();
 long left_size = source_channel.size();
 long position = 0;
 while (left_size > 0) {
 long write_size = source_channel.transferto(position, left_size, dest_channel);
 position += write_size;
 left_size -= write_size;
 }
 source_channel.close();
 source_file.close();
 dest_channel.close();
 dest_file.close();
 }
 
 
 public static void main(string[] args) {
 try {
 long start_time = system.currenttimemillis();
 bigfilecopy.copybychanneltochannel("source_file", "dest_file");
 long end_time = system.currenttimemillis();
 system.out.println("copy time = " + (end_time - start_time));
 } catch (ioexception e) {
 e.printstacktrace();
 }
 }
 
}

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网