Reputation: 330
Asked this question, having already tried possible solutions in other questions here on stack but that didn't allow me to fix the problem.
As in the title, I have created a java utility with which I have to perform operations on text files, in particular I have to perform simple operations to move between directories, copy from one directory to another, etc.
To do this I have used the java libraries java.io.File
and java.nio.*
, And I have implemented two functions for now,copyFile(sourcePath, targetPath)
and moveFile(sourcePath, targetPath)
.
To develop this I am using a mac, and the files are under the source path /Users/myname/Documents/myfolder/F24/archive/
, and my target path is /Users/myname/Documents/myfolder/F24/target/
.
But when I run my code I get a java.nio.file.NoSuchFileException: /Users/myname/Documents/myfolder/F24/archive
Having tried the other solutions here on stack and java documentation already I haven't been able to fix this yet ... I accept any advice or suggestion
Thank you all
// copyFile: funzione chiamata per copiare file
public static boolean copyFile(String sourcePath, String targetPath){
boolean fileCopied = true;
try{
Files.copy(Paths.get(sourcePath), Paths.get(targetPath), StandardCopyOption.REPLACE_EXISTING);
}catch(Exception e){
String sp = Paths.get(sourcePath)+"/";
fileCopied = false;
System.out.println("Non posso copiare i file dalla cartella "+sp+" nella cartella "+Paths.get(targetPath)+" ! \n");
e.printStackTrace();
}
return fileCopied;
}
Upvotes: 1
Views: 1256
Reputation: 109547
Not sure whether my comment is understood though answered.
Ìn java SE target
must not be the target directory. In other APIs of file copying
one can say COPY FILE TO DIRECTORY
. In java not so; this was intentionally designed to remove one error cause.
That style would be:
Path source = Paths.get(sourcePath);
if (Files.isRegularFile(source)) {
Path target = Paths.get(targetPath);
Files.createDirectories(target);
if (Files.isDirectory(target)) {
target = Paths.get(targetPath, source.getFileName().toString());
// Or: target = target.resolve(source.getFileName().toString());
}
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
}
Better ensure when calling to use the full path.
Upvotes: 2
Reputation: 102795
Files.copy
cannot copy entire directories. The first 'path' you pass to Files.copy
must ALL:
Files.move
can (usually - depends on impl and underlying OS) usually be done to directories, but not Files.copy
. You're in a programming language, not a shell. If you want to copy entire directories, write code that does this.
Upvotes: 2