我在一个文件夹中列出了文件,然后我必须将它们转移到另一个文件夹中。但是,我遇到的问题如下...当尝试将它们粘贴到其他文件夹时,路径类似于 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
谢谢四位!
最佳答案
您无法将目录传递给 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);
}
}
}
}
关于java - 如何将文件复制到其他目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47000400/