Python 官方文档:入门教程 => 点击学习
本文实例为大家分享了Java多线程实现复制文件的具体代码,供大家参考,具体内容如下 代码实现如下: package com.tulun.thread; import java.i
本文实例为大家分享了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) {
}
}
}
}
}
运行结果:
--结束END--
本文标题: Java多线程实现复制文件
本文链接: https://www.lsjlt.com/news/142025.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0