多线程拷贝程序主要有四个类组成:WorkThread类,ReadFrom类,WriteTo类,ExpressCopy类
WorkTread类:主要负责文件拷贝的线程类
ReadFrom类:主要负责从源文件读取数据到缓冲区
WriteTo类:主要负责把缓冲区的数据写进新的文件
ExpressCopy类:类似于测试类,以上3个是核心代码
WorkThread类
package copy1;
import java.io.FileNotFoundException;
import java.io.IOException;
public class WorkThread extends Thread
{
private long begin,end;//文件块读取的起始和结束位置
private String sourceFile,desFile;
public WorkThread(long begin, long end, String sourceFile, String desFile)
{
this.begin=begin;
this.end=end;
this.sourceFile=sourceFile;
this.desFile=desFile;
}
public void run()
{
byte[] buffer=new byte[4096];//设置缓冲区
int len=0;
try
{
ReadFrom rf=new ReadFrom(this.sourceFile);
WriteTo wt=new WriteTo(this.desFile);
long startTime=System.currentTimeMillis();
while(begin<end)
{
len=rf.read(buffer, begin);
//判断读取的数据是否超出了文件块的结束位置end
if(begin+len>end) len=(int)(end-begin);
wt.write(buffer, len, begin);
begin+=len;//起始位置往前移动len个字节
}
rf.close();
wt.close();
long endTime=System.currentTimeMillis();
System.out.println(endTime-startTime);
}catch(IOException e)
{
e.printStackTrace();
}
}
}
ReadFrom类
package copy1;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class ReadFrom
{
private RandomAccessFile from;
public ReadFrom(String fromFile) throws FileNotFoundException
{
this.from=new RandomAccessFile(fromFile, "r");
}
//同步文件读取操作
synchronized public int read(byte[] buffer, long pos) throws IOException
{
from.seek(pos);
return from.read(buffer);
}
//关闭随机文件访问流,释放相关系统资源
public void close() throws IOException
{
from.close();
}
}
WriteTo类
package copy1;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class WriteTo
{
private RandomAccessFile to;
public WriteTo(String toFile) throws FileNotFoundException
{
to=new RandomAccessFile(toFile,"rw");
}
//同步文件写入操作
synchronized public void write(byte[] buffer,int len, long pos) throws IOException
{
to.seek(pos);
to.write(buffer, 0, len);
}
//关闭随机文件访问流,释放相关系统资源
public void close() throws IOException
{
to.close();
}
}
ExpressCopy类
package copy1;
import java.io.File;
import java.io.IOException;
public class ExpressCopy
{
private String sourceFilePath;//源文件路径
private String desFilePath;//目标文件路径
public ExpressCopy()
{
//没用GUI,直接在源程序上初始化参数
this.sourceFilePath="";
this.desFilePath="";
}
public void work()
{
File f=new File(sourceFilePath);
//判断文件是否存在或是否为空文件
if(!f.exists()||f.length()==0)
{
System.out.println("The source file"+sourceFilePath+"does not exist or its length is 0");
}
long len=f.length();
try
{
Thread[] t=new Thread[2];
//用2个线程的原因是因为经本人测试,用2个线程时比单线程时快,但用3个线程的时候却比单个线程还慢
for(int i=0;i<2;i++)
{
t[i]=new WorkThread(i*len/2,(i+1)*len/2,sourceFilePath,desFilePath);
System.out.println("第"+i+"个线程已经启动");
t[i].start();
}
}catch(Exception e)
{
e.printStackTrace();
}
}
}
小弟是一个java初学者,如果文章中有什么不对的地方或兄台有更好的解决方案,还望不吝赐教,给我留言