package com.wxh.random;
import java.io.*;
/**
* 多线程拷贝文件
*
* @author Administrator
*
*/
public class ThreedRandomAccessFileDemo {
public static void main(String[] args) throws IOException {
File source = new File("E:\\test\\a.txt");
File target = new File("E:\\copy");
copyFileByThread(source, target);
}
private static void copyFileByThread(File source, File target)
throws IOException {
if (!target.exists()) {
target.mkdirs();
}
File file = new File(target, source.getName());
if (!file.exists()) {
file.createNewFile();
}
// 循环开启线程
int threadCount = 3;
long unitLength = source.length() / threadCount;
for (int i = 0; i < threadCount; i++) {
long start = unitLength * i;
long end = source.length();
new CopyThread(source, file, start, end).start();
}
}
static class CopyThread extends Thread {
File source;
File target;
long start;
long end;
public CopyThread(File source, File target, long start, long end) {
this.source = source;
this.target = target;
this.start = start;
this.end = end;
}
@Override
public void run() {
RandomAccessFile reader = null;
RandomAccessFile writer = null;
try {
reader = new RandomAccessFile(source, "rw");
writer = new RandomAccessFile(target, "rw");
writer.setLength(source.length());
byte[] buf = new byte[100];
reader.seek(start);
writer.seek(start);
long finished = start;
while (finished < end) {
if (finished + buf.length >= end) {
reader.read(buf, 0, (int) (end - finished));
writer.write(buf, 0, (int) (end - finished));
} else {
reader.read(buf);
writer.write(buf);
}
finished += buf.length;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getId() + "拷贝完毕");
}
}
}
}
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
java线程池拷贝文件 java 多线程复制文件
Java多线程复制文件
java线程池拷贝文件 源文件 分块 目标文件