Error in method when moving files from one directory to another

2

In a method where I move files, when I pass the parameters and perform the operation, I always get an error. If something is failing me, could you help me?

public void MoverArchivo(String oldPath, String oldName, String newPath) {
    File f = null;
    File f1 = null;
    boolean bool = false;
    try {      
        f = new File(oldPath+oldName);
        f1 = new File(newPath+oldName);

        if(f.renameTo(new File(newPath+oldName))) {
            System.out.println("Archivo removido");
        } else {
            System.out.println("El archivo "+ oldName + " no pudo ser cambiado de destino");
        }
    } catch(Exception e) {
        System.out.println("ADVERTENCIA: El archivo " + oldName + " no pudo ser cambiado de destino, CAUSA:" + e);
    }
    System.out.println("Termina archivo "+oldName);
    System.out.println("----------------------------------------------------------------");
}
    
asked by Kevin M. 15.02.2016 в 16:37
source

3 answers

2

Based on your answer , I recommend that to avoid problems with these cases, use the constructor File(String, String) , which abstracts the problems you have when you add the folder separation character:

In this way, your code:

f = new File(oldPath+oldName);
f1 = new File(newPath+oldName);

Changes to:

f = new File(oldPath, oldName);
f1 = new File(newPath, oldName);
    
answered by 15.02.2016 / 17:33
source
2

I already found my error, apparently, when assigning the old directory the last folder with the file was concatenated, making an address not valid, for example:

Users/soporte02/Desktop/Carpeta1ArchivoEjemplo.pdf

What I had to do was simply concatenate him by assigning the old and new directory, a double diagonal // to finally end up like this:

Users/soporte02/Desktop/Carpeta1/ArchivoEjemplo.pdf

The method now stayed like this:

    public void MoverArchivo(String oldPath, String oldName, String newPath)
    {
        File f = null;
        boolean bool = false;
        try{      
                f = new File(oldPath + "//" + oldName);

                if(f.renameTo(new File(newPath+ "//" + oldName)))
                {
                    System.out.println("Archivo reubicado");
                }
                    else
                {
                    System.out.println("El archivo "+ oldName + " no pudo ser cambiado de destino");
                }
            }
        catch(Exception e)
        {
            e.printStackTrace(System.out);
        }
    }

This method I use in a cycle to move all files only PDF, from one folder to another.

    
answered by 15.02.2016 в 17:28
0

Try to comment on this line:

f1 = new File(newPath+oldName);

If I'm not wrong, when doing that line create the file and then when you want to move the name, it has been reserved to create a file there, then it gives you an error.

If you have more questions, read the following link:

link

    
answered by 15.02.2016 в 17:10