【java工具方法】複製目錄或文件

工具方法

/**
	/**
	 * 複製文件或目錄
	 * 
	 * @author 靜心事成
	 * @param source 源文件/目錄路徑
	 * @param target 目標文件/目錄路徑
	 * @param isOverwrite 是否覆蓋目標文件
	 * @throws IOException 
	 * */
	public static void copy(File source, File target, boolean isOverride) throws IOException {
		// 定義變量,保存是否需要覆蓋目標文件的常量
		final StandardCopyOption option = isOverride ? StandardCopyOption.REPLACE_EXISTING : StandardCopyOption.COPY_ATTRIBUTES;
		// 判斷source是否是文件,如果是文件,直接進行復制
		if (source.isFile())
			// 使用Java SE 7的Files.copy方法直接複製
			Files.copy(source.toPath(), target.toPath(), option);
		else {
			// 如果source是目錄
			// 判斷目標目錄是否存在
			if (!target.exists())
				// 新建目標目錄
				target.mkdirs();
			// 查找源目錄下的所有文件和目錄
			File[] sourceFiles = source.listFiles();
			// 遍歷複製
			for (File file : sourceFiles) {
				// 判斷是文件還是目錄
				if (file.isFile()) 
					// 使用Java SE 7的Files.copy方法直接複製
					Files.copy(file.toPath(), Paths.get(target.getPath(), file.getName()), option);
				else 
					// 目錄的話,遞歸調用本方法進行復制
					copy(file, new File(target.getPath() + File.separator + file.getName()), isOverride);
			}
		}
	}
	
	/**
	 * 複製文件或目錄
	 * copy(File, File, boolean)的重載方法
	 * 
	 * @author 靜心事成
	 * @param source 源文件/目錄路徑
	 * @param target 目標文件/目錄路徑
	 * @param isOverwrite 是否覆蓋目標文件
	 * @throws IOException 
	 * */
	public static void copy(String source, String target, boolean isOverride) throws IOException {
		copy(new File(source), new File(target), isOverride);
	}

引用的類

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

相關方法

示例

	public static void main(String[] args) {
		String source = "D:\\imgPath";
		String target = "D:\\imgPath2";
		try {
			copy(source, target, true);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

捐贈

若你感覺讀到這篇文章對你有啓發,能引起你的思考。請不要吝嗇你的錢包,你的任何打賞或者捐贈都是對我莫大的鼓勵。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章