java调用CMD完成文件复制
最近突然又想起文件的复制操作,感觉用流的方式操作还是不免有些费劲,所以试着在程序中结合cmd的方式处理,非常之方便,效率很快,大家不妨试试哦。
package utils;
import java.io.File;
import java.io.IOException;
/**
* Created by Lemostic on 2016/7/25.
*/
public class CopyUtil {
public static void main(String[] args) {
//复制文件从d:\001\002到d:\001\002\003\cust
copyFile("iii.txt", "d:\\001\\002", "d:\\001\\002\\003\\", "cust");
}
/**
* 将指定目录下的文件复制到目标文件夹下
*
* @param fileName 源文件名
* @param sourcePath 源文件路径
* @param destPath 目标文件路径
*/
public static void copyFile(String fileName, String sourcePath, String destPath) {
File file = null;
if (sourcePath != null && !"".equals(sourcePath)) {
file = sourcePath.endsWith("\\") ? new File(sourcePath + fileName) : new File(sourcePath + "\\" + fileName);
if (!file.exists()) {
System.out.println("无法找到源文件目录[" + sourcePath + "]或源文件[" + fileName + "]不存在,无法完成复制!");
}
}
File destFilePath = new File(destPath);
if (!destFilePath.exists()) {
destFilePath.mkdirs();
System.out.println("成功创建目录" + destPath);
}
StringBuilder cmd = new StringBuilder("cmd.exe /c copy ");//关于java调用cmd的参数可以自行百度
cmd.append(sourcePath + "\\" + fileName + " ").append(destPath + " ");
try {
Runtime.getRuntime().exec(cmd.toString());
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(cmd.toString());
}
/**
* 复制到指定文件夹下的自定义目录
* @param fileName 源文件名
* @param sourcePath 源文件路径
* @param destPath 目标文件路径
* @param customPath 自定义文件目录
*/
public static void copyFile(String fileName, String sourcePath, String destPath, String customPath) {
if (customPath == null || "".equals(customPath)) {
customPath = "";
}
destPath = destPath + "\\" + customPath;
copyFile(fileName, sourcePath, destPath);
}
}