Java loses the last "/" character of the path

143 views Asked by At

I am developing a java application to perform operations with files. In particular, I perform move and copy of files .. and I have programmed two functions. Functions take strings such as sourcePath and targetPath as parameters. I am developing on a mac, and I have given 777 permissions to the folders I need. But I have the problem, that when I pass paths to the copyFile and moveFile functions I lose the last "/" of the path and consequently get a java.nio.File: NoSuchFileException exception. I have read both the Java and online documentation but have not found any answers.

I accept any suggestion or advice ... I just add that by manually forcing the path inside the function, then not passing sourcePath and targetPath, the two functions behave as they should.

  • copyFile:
public static boolean copyFile(String sourcePath, String targetPath) throws IOException {

        boolean fileCopied = true;
        // if i pass sourcePath i lost the last /
        File dirFiles = new File("/Users/myname/Documents/deleghe/remote/F24_CT/deleghe_da_inviare_a_icbpi/");
        File[] listOfFiles = dirFiles.listFiles();
        String dest = "/Users/myname/Documents/deleghe/local/F24_CT/deleghe_da_inviare_a_icbpi/";
        for (File file : listOfFiles) {
            Files.copy(file.toPath(),
                    (new File(dest + file.getName())).toPath(),
                    StandardCopyOption.REPLACE_EXISTING);
        }

        return fileCopied;
    }
  • moveFile:
public static boolean moveFile(String sourcePath, String targetPath) throws IOException {

        boolean fileMoved = true;
        // if i pass sourcePath i lost the last /
        File dirFiles = new File("/Users/myname/Documents/deleghe/remote/F24_CT/deleghe_da_inviare_a_icbpi/");
        File[] listOfFiles = dirFiles.listFiles();
        String dest = "/Users/myname/Documents/deleghe/remote/F24_CT/deleghe_inviate/";
        for (File file : listOfFiles) {
            if (file.length() >= 968 && file.length() <= 2057) {
                Files.move(file.toPath(),
                        (new File(dest + file.getName())).toPath(),
                        StandardCopyOption.REPLACE_EXISTING);
                System.out.println("File spostato correttamente: " + file.getName() + "!! \n");
            } else {
                System.out.println("Non รจ stato possibile spostare il file: " + file.getName() + "!! \n");
            }
        }

        return fileMoved;
    }
1

There are 1 answers

1
Azamat Aminov On
  1. try to use Paths.get(dest, file.getName()).toUri() instead of dest + file.getName() (it is not best practice)
  2. you are not losing anything, you just reading files from directory and your code is working without any exception. Check your directories and files inside them one more time