使用java怎么实现一个大文件拷贝功能?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
Java的特点有哪些
Java的特点有哪些
1.Java语言作为静态面向对象编程语言的代表,实现了面向对象理论,允许程序员以优雅的思维方式进行复杂的编程。
2.Java具有简单性、面向对象、分布式、安全性、平台独立与可移植性、动态性等特点。
3.使用Java可以编写桌面应用程序、Web应用程序、分布式系统和嵌入式系统应用程序等。
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();
}
}
}
看完上述内容,你们掌握使用java怎么实现一个大文件拷贝功能的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注天达云行业资讯频道,感谢各位的阅读!