java调用CMD完成文件复制

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);
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值