【java工具方法】复制单个文件

工具方法

/**
	 * 拷贝文件,将单个文件拷贝到另一个目录
	 * 
	 * @author 静心事成
	 * @param source 源文件
	 * @param target 目标文件
	 * @param isOverwrite 是否覆盖目标文件
	 * @return target.toPath() 目标文件路径
	 * @throws IOException 
	 * */
	public static Path copy(File source, File target, boolean isOverride) throws IOException {
		// 使用java 7的新特性方法
		return Files.copy(source.toPath(), target.toPath(), isOverride ? StandardCopyOption.REPLACE_EXISTING : StandardCopyOption.COPY_ATTRIBUTES);
	}
	
	/**
	 * 拷贝文件,将单个文件拷贝到另一个目录
	 * Path(File, File, boolean)的重载方法
	 * 
	 * @param source 源文件路径
	 * @param target 目标文件路径
	 * @param isOverwrite 是否覆盖目标文件
	 * @return target.toPath() 目标文件路径	 
	 * @throws IOException 
	 * */
	public static Path copy(String source, String target, boolean isOverride) throws IOException {
		return 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.Path;
import java.nio.file.StandardCopyOption;

示例

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

捐赠

若你感觉读到这篇文章对你有启发,能引起你的思考。请不要吝啬你的钱包,你的任何打赏或者捐赠都是对我莫大的鼓励。

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