Java代码实现复制一个文件到指定目录下,且文件名不变

package file;

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

public class Copy {
    static boolean flag = false;

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stu
        String s1 = "D:\\xxx.txt";
        String s2 = "E:\\my\\xxx.txt";
        if (copy(s1, s2)) {
            System.out.println("复制成功");
        } else {
            System.out.println("复制失败");
        }
    }

    private static void copyFiles(String target, String source) throws IOException {
        Files.copy(Paths.get(source), Paths.get(target), StandardCopyOption.REPLACE_EXISTING);
        flag = true;
    }

    static boolean copy(String s1, String s2) throws IOException {
        File wjj = new File("E://my");
        if (wjj.exists()) {
            copyFiles(s2, s1);
        } else {
            Files.createDirectories(Paths.get("E://disport"));
            copyFiles(s2, s1);
        }
        return flag;
    }

}

发布了31 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_41638825/article/details/81156505