//1.新建 ManyThreadCopyFileTask类
package com.za.java_thread.test1;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Date;
public class ManyThreadCopyFileTask implements Runnable{
private long start;//起始位置
private long total;//总量
private File srcFile;
private File toFile;
public ManyThreadCopyFileTask(File srcFile,File toFile,long start,long total) {
super();
this.start = start;
this.total = total;
this.srcFile=srcFile;
this.toFile=toFile;
}
//Date d=new Date();
@Override
public void run() {
try {
copyFile(start,srcFile, toFile);
//System.out.println(d);
System.out.println(Thread.currentThread().getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
//传参
/*private static final String SRCFILE="D:\\myeclipse2014pj (1)\\myeclipse-pro-2014-GA-offline-installer-windows.exe";
private static final String TOFILE="E:\\myeclipse2014.exe";
*/
public void copyFile(long start,File srcFile, File toFile) throws FileNotFoundException {
FileInputStream fileInputStream = null;
//FileOutputStream fileOutputStream = null;
RandomAccessFile randomAccessFile = new RandomAccessFile(toFile,"rw");
try {
fileInputStream = new FileInputStream(srcFile);
//fileOutputStream = new FileOutputStream(toFile);
// 定义流容器
byte[] container = new byte[1024];
// 读取文件
int length = 0;
fileInputStream.skip(start);//跳过字节数
randomAccessFile.seek(start);
int count=(int) (this.total/1024);
if(this.total%1024!=0) {//一个线程所处理的
count++;
}
while(count-- > 0) {
if((length = fileInputStream.read(container))!=-1)
//length = fileInputStream.read(container);
randomAccessFile.write(container, 0, length);
/*else
break;*/
}
/*while ((length = fileInputStream.read(container)) != -1) {
// 写入文件
randomAccessFile.write(container, 0, length);
}*/
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fileInputStream != null)
fileInputStream.close();
if (randomAccessFile != null)
randomAccessFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2.新建 ManyThreadCopyFileTest测试类
package com.za.java_thread.test1;
import java.io.File;
import java.util.Date;
import com.za.java_thread.tests.ThreadCopyFile;
public class ManyThreadCopyFileTest {
public static void main(String[] args) {
Date d=new Date();
File file=new File("D:/myeclipse2014pj (1)/myeclipse-pro-2014-GA-offline-installer-windows.exe");
File toFile=new File("E:/1.exe");
long fileTotal=file.length();
int duan=10,iduan=10;// duan用于循环 iduan分多少段
long each=fileTotal/duan;
long leave=fileTotal%duan;
while(duan-->0) {//每次循环都创建一个线程,并且启动
new Thread(new ManyThreadCopyFileTask(file,toFile,(iduan-duan-1)*each,each)).start();
//long l1=System.currentTimeMillis();
System.out.println(d);
}
if(leave>0) {
new Thread(new ManyThreadCopyFileTask(file,toFile,(iduan)*each,leave)).start();
System.out.println(d);
}
}
}