Java多线程实现复制文件
短信预约 -IT技能 免费直播动态提醒
本文实例为大家分享了Java多线程实现复制文件的具体代码,供大家参考,具体内容如下
代码实现如下:
package com.tulun.thread;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
public class ThreadCopyFile {
public static void main(String[] args) throws Exception {
File file = new File("D:\\demo\\erke\\test.txt");
startThread(5, file.length(), "D:\\demo\\erke\\test.txt",
"D:\\demo\\erke\\test1.txt");
}
public static void startThread(int threadnum, long fileLength, String sourseFilePath, String desFilePath) {
System.out.println(fileLength);
long modLength = fileLength % threadnum;
System.out.println("modLength:" + modLength);
long desLength = fileLength / threadnum;
System.out.println("desLength:" + desLength);
for (int i = 0; i < threadnum; i++) {
System.out.println((desLength * i) + "-----" + (desLength * (i + 1)));
new FileWriteThread((desLength * i), (desLength * (i + 1)), sourseFilePath, desFilePath).start();
}
if (modLength != 0) {
System.out.println("最后的文件写入");
System.out.println((desLength * threadnum) + "-----" + (desLength * threadnum + modLength));
new FileWriteThread((desLength * threadnum), desLength * threadnum + modLength + 1, sourseFilePath,
desFilePath).start();
}
}
static class FileWriteThread extends Thread {
private long begin;
private long end;
private RandomAccessFile sourseFile;
private RandomAccessFile desFile;
public FileWriteThread(long begin, long end, String sourseFilePath, String desFilePath) {
this.begin = begin;
this.end = end;
try {
this.sourseFile = new RandomAccessFile(sourseFilePath, "rw");
this.desFile = new RandomAccessFile(desFilePath, "rw");
} catch (FileNotFoundException e) {
}
}
public void run() {
try {
sourseFile.seek(begin);
desFile.seek(begin);
int hasRead = 0;
byte[] buffer = new byte[1];
while (begin < end && -1 != (hasRead = sourseFile.read(buffer))) {
begin += hasRead;
desFile.write(buffer, 0, hasRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
sourseFile.close();
desFile.close();
} catch (Exception e) {
}
}
}
}
}
运行结果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341