如何将文件复制到其他目录

时间:2017-10-29 12:55:40

标签: java

我将文件列在一个文件夹中,然后我必须将它们转移到另一个文件夹中。但是,我得到的问题是以下...当尝试将它们粘贴到另一个文件夹时,路径就像E:\ Files,这会导致我生成某种文件,它不会像我一样坚持我。我尝试了几种方法仍然无法做到,我留下我的代码,看看你是否可以帮助我

 Path algo = Paths.get("E:/Files/");
   public void Copy(String origenArchivo, Path algo) {
                Path origenPath = Paths.get(origenArchivo);
                String s = algo.toAbsolutePath().toString();
                System.out.println(s);
                Path destinoPath = Paths.get(s);
                System.out.println(destinoPath);
                String x = destinoPath.toString() + "/";

                Path conv = Paths.get(x);
                System.out.println(conv);
        try {

            Files.copy(origenPath, conv, StandardCopyOption.REPLACE_EXISTING);
               } catch (IOException ex) {
            Logger.getLogger(Metodos.class.getName()).log(Level.SEVERE, null, ex);
        }



    }




 File dir = new File("C:/Users/PC/Desktop/");
        public void TravelToFantasy(File dir) {
        File listFile[] = dir.listFiles();
        if (listFile != null) {
            for (int i = 0; i < listFile.length; i++) {
                if (listFile[i].isDirectory()) {
                    Copy(listFile[i]);
                } else {
                    System.out.println(listFile[i].getPath());
                    System.out.println(destino);
                    this.Copy(listFile[i].getPath(), algo);

                }
            }
        }
         }

我试图将“/”放到Paths.get获取我的路径上,但它总是最终离开我的路径为E:\ Files

非常感谢你!

2 个答案:

答案 0 :(得分:1)

您无法将目录传递给Files.copy。

您不需要在字符串之间进行所有转换。只需使用Path.resolve代替:

public void copy(String origenArchivo, Path algo)
throws IOException {
    Path origenPath = Paths.get(origenArchivo);
    Path conv = algo.resolve(origenPath.getFileName());
    Files.copy(origenPath, conv, StandardCopyOption.REPLACE_EXISTING);
}

作为旁注,Path / Paths / Files类优于java.io.File类,因为它们在操作失败时提供有意义的信息。你根本不应该使用java.io.File:

Path dir = Paths.get("C:/Users/PC/Desktop/");

public void TravelToFantasy(Path dir)
throws IOException {
    try (DirectoryStream<Path> listFile = Files.newDirectoryStream(dir)) {
        for (Path file : listFile) {
            if (Files.isDirectory(file)) {
                Copy(file);
            } else {
                System.out.println(file);
                System.out.println(destino);
                this.Copy(file, algo);
            }
        }
    }
}

答案 1 :(得分:0)

使用java.io.File.separator而不是“/”,这将有助于您的代码运行任何操作系统。