【1】一个线程复制一个文件
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class MyThread extends Thread {
@Override
public void run() {
String srcFile="初恋未满.mp3";
String aimFile="初恋未满2.mp3";
FileInputStream in=null;
FileOutputStream out=null;
try {
in=new FileInputStream(srcFile);
out=new FileOutputStream(aimFile);
int len=0;
byte[] bytes=new byte[1024*8];
while ((len=in.read(bytes))!=-1){
out.write(bytes,0,len);
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(in!=null){
in.close();
}if (out!=null){
out.close();}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class CopyFile {
public static void main(String[] args) {
MyThread myThread=new MyThread();
myThread.start();
}
}
【2】多个线程复制同一个文件
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class MyThread extends Thread {
long start;
long end;
RandomAccessFile srcIN;//文件随机访问流
RandomAccessFile aimOUT;
MyThread (long start,long end,String file,String file3) throws FileNotFoundException {
this.start=start;
this.end=end;
this.srcIN=new RandomAccessFile(file,"rw");
this.aimOUT=new RandomAccessFile(file3,"rw");
}
@Override
public void run() {
try {
srcIN.seek(start);//定义指针位置
aimOUT.seek(start);
int len=0;
byte[] bytes=new byte[1024*8];
long filePointer=srcIN.getFilePointer();
while((start<end)&&(len=srcIN.read(bytes))!=-1){
start+=len;
System.out.println(len);
aimOUT.write(bytes,0,len);
}
srcIN.close();
aimOUT.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.File;
import java.io.FileNotFoundException;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
File file= new File("初恋未满.mp3");
long lenth=file.length();
System.out.println("文件的总长度是:"+lenth);
long threadNum=3;
//线程1 1-100
//线程2 100-200
//线程3 200-300
long avlenth=lenth/threadNum;
for (int i = 0; i <threadNum ; i++) {
long start=avlenth*i;//每个线程开始复制文件的位置
long end=(i+1)*avlenth;//每个线程结束复制文件的位置
//知道开始位置和结束位置之后,可以开启一个线程
new MyThread(start,end,"初恋未满.mp3","初恋未满3.mp3").start();
}
//如果有剩余字节不够我们预先设定的线程数分,就再补一个线程,来COPY剩下的字节
long last=lenth%threadNum;
if(last!=0){
long start=threadNum*avlenth;
long end=threadNum*avlenth+last;
new MyThread(start,end,"初恋未满.mp3","初恋未满3.mp3").start();
}
System.out.println("OVER!");
}