Java - renameTo

1

I put the code first and then explain the problem. I can not find what is wrong.

String nuevoNombre = archivo.getParentFile() + "\proc_" + archivo.getName();

File newfileName = new File(nuevoNombre);

return archivoProcesado.renameTo(newfileName);

If I run it from my machine, it works fine. The issue is that when running from a server (it has jre 1.4) renameTo returns false , and does not rename the file.

It does not throw any exception, or security or anything. Simply false and do not rename. Any idea why this can happen and how can I solve it?

    
asked by Fernando 09.06.2017 в 14:00
source

3 answers

3

The expected behavior of this method differs from what was expected in the most modern ones. link

Later Oracle changed the behavior for what we know today as renameTo

You can use an alternative, deleting the old file and saving the new one in the new location or with the new name.

    
answered by 09.06.2017 в 14:04
1

In the docs of File.renameTo warns that

  

Many aspects of the behavior of this method are inherently   platform-dependent: The rename operation might not be able to move to   file from one filesystem to another, it might not be atomic, and it   might not succeed if a file with the destination abstract pathname   already exists.

Above all, it occurs to me that you should see if you are trying to move the file between different partitions. In such a case, it is very likely to fail. Also if the source or destination file is opened by another process.

As suggested by in SO the alternative is copy and delete by hand, or use FileUtils. moveFile from Apache Commons.

Although you probably already know, at this point Jre 1.4 is a very old version (if it is in your power, you should try to migrate to a more modern version).

    
answered by 09.06.2017 в 14:39
0

Rename a file in Java

The java.io.File class implements the renameTo method that allows renaming a file.

Example, changing the name of a file "example1.txt" to "example2.txt":

package mx.com.softmolina;

import java.io.File;

/**

 * @author SoftMolina

 */

public class RenombrarArchivo {

    public static void main(String args[]){

            try{
            File archivo1 = new File("ejemplo1.txt");

            File archivo2 = new File("ejemplo2.txt");

            boolean estatus = archivo1.renameTo(archivo2);

            if (!estatus) {

                System.out.println("Error no se ha podido cambiar el nombre al archivo");

            }else{

                System.out.println("Cambio de nombre del archivo exitoso");

            }
            }catch(Exception e){
            System.out.println(e);

           }

    }

}

The file name change may fail because the file does not exist, the user does not have permission to change the name, or the file is in use.

See more here

    
answered by 09.06.2017 в 18:07