Java多線程複製檔案(轉)__Java
來源:互聯網
上載者:User
package mastercn;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.RandomAccessFile;
public class CopyFile implements Runnable {
// 來源檔案
private String sourceFileName;
// 目標檔案
private String targetFileName;
// 分塊總數
private int blockCount;
// 開始COPY的塊序號
private int blockNo;
// 緩衝大小
private int maxBuffSize = 1024 * 1024 ;
/**
* 將sourceFileName檔案分blockCount塊後的第blockNo塊複製至sourceFileName
* @param sourceFileName 來源檔案全名
* @param targetFileName 目標檔案全名
* @param blockCount 檔案分塊COPY數
* @param blockNo 開始COPY的塊序號
*/
public CopyFile(String sourceFileName,String targetFileName, int blockCount, int blockNo)
{
this .sourceFileName = sourceFileName;
this .targetFileName = targetFileName;
this .blockCount = blockCount;
this .blockNo = blockNo;
}
public void run() {
// 得到來源檔案
File file = new File(sourceFileName);
// 得到來源檔案的大小
long size = file.length();
// 根據檔案大小及分塊總數算出單個塊的大小
long blockLenth = size / blockCount;
// 算出當前開始COPY的位置
long startPosition = blockLenth * blockNo;
// 執行個體化緩衝
byte [] buff = new byte [maxBuffSize];
try {
// 從源檔案得到輸入資料流
InputStream inputStream = new FileInputStream(sourceFileName);
// 得到目標檔案的隨機訪問對象
RandomAccessFile raf = new RandomAccessFile(targetFileName, " rw " );
// 將目標檔案的指標位移至開始位置
raf.seek(startPosition);
// 當前讀取的位元組數
int curRedLength;
// 累計讀取位元組數的和
int totalRedLength = 0 ;
// 將來源檔案的指標位移至開始位置
inputStream.skip(startPosition);
// 依次分塊讀取檔案
while ((curRedLength = inputStream.read(buff)) > 0 && totalRedLength < blockLenth)
{
// 將緩衝中的位元組寫入檔案?目標檔案中
raf.write(buff, 0 , curRedLength);
// 累計讀取的位元組數
totalRedLength += curRedLength;
}
// 關閉相關資源
raf.close();
inputStream.close();
} catch (Exception ex)
{
ex.printStackTrace();
}
}
}
Test.java
package mastercn;
public class Test {
/**
* @param args
*/
//來源檔案
private static String sourceFile;
//目標檔案
private static String targetFile;
//分塊數
private static int blockCount;
public static void main(String[] args) {
// TODO Auto-generated method stub
//
sourceFile=args[0];
targetFile=args[1];
blockCount=Integer.parseInt(args[2]);
//記錄開始時間
long beginTime=System.currentTimeMillis();
//依次分塊進行檔案COPY
for(int i=0;i<blockCount;i++)
{
//執行個體化檔案複製對象
CopyFile copyFile=new CopyFile(sourceFile,targetFile,blockCount,i);
//執行個體化線程
Thread thread=new Thread(copyFile);
//開始線程
thread.start();
try
{
//加入線程
thread.join();
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
//計算耗時
long endTime=System.currentTimeMillis();
//輸出耗時
System.out.println("共用時:"+(endTime-beginTime)+"ms");
}
}