1. 程式人生 > >Java -- 多執行緒檔案複製

Java -- 多執行緒檔案複製

題目描述:

  • 實現檔案複製功能
  • 多執行緒實現檔案從一個目錄複製到另一個目錄
  • @param sourceFile : 給定原始檔路徑名
  • @param desPath : 複製點檔案路徑

在這裡插入圖片描述 程式碼:

package fileio20180924;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.omg.CORBA.PUBLIC_MEMBER;

/**
 * 實現檔案複製功能
 * 多執行緒實現檔案從一個目錄複製到另一個目錄
 * @param sourceFile : 給定原始檔路徑名
 * @param desPath : 複製點檔案路徑
 * @author Cue
 *
 */

public class FileCopy extends Thread {
	private File sourceFile;//待讀取的原始檔
	private File desPath;//待寫入的目標檔案
	
	public FileCopy(String sourceFile,String desPath){
		this.sourceFile = new File(sourceFile);
		this.desPath = new File(desPath);
	}
	
	public void run(){
		FileInputStream in = null;
		FileOutputStream out = null;
		
	try{	
		in = new FileInputStream(sourceFile);
		out = new FileOutputStream(desPath);
		
		byte[] b = new byte[1024];
		int length = 0;
		
		//獲取原始檔大小
		long len = sourceFile.length();
		//已複製檔案的位元組數
		double temp = 0;
		//數字格式化,顯示百分比
		DecimalFormat dFormat = new DecimalFormat("##.00%");
		while((length = in.read(b)) != -1){
			//輸出位元組
			out.write(b, 0, length);
			//獲取已下載的大小,並且轉換成百分比
			temp += length;
			double d = temp/len;
			System.out.println(sourceFile.getName() + "已複製的進度 :"+dFormat.format(d));
		}
		System.out.println(sourceFile.getName() + "複製完成!");
	}catch(FileNotFoundException e){
		e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}finally{
			try{
				if(in != null){
					in.close();
				}
				if(out != null){
					out.close();
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		FileCopy cf = new FileCopy("C:\\Users\\小玉沉香\\Desktop\\source\\1.txt","C:\\Users\\小玉沉香\\Desktop\\desPath\\11.txt");
		FileCopy cf2 = new FileCopy("C:\\Users\\小玉沉香\\Desktop\\source\\2.txt","C:\\Users\\小玉沉香\\Desktop\\desPath\\22.txt");
		FileCopy cf3 = new FileCopy("C:\\Users\\小玉沉香\\Desktop\\source\\3.txt","C:\\Users\\小玉沉香\\Desktop\\desPath\\33.txt");
		cf.start();
		cf2.start();
		cf3.start();
	}

}

輸出結果: 在這裡插入圖片描述