How to rename an existing file?

I have 2 files, File src = new File("loc/xyz.mp3") and File dst=new File("loc/xyz1.mp3") Now I want to rename dst to xyz.mp3, and delete src . How can i do this? I have tried,

 src.delete(); dst.renameTo(src); 

I run this in AsyncTask in the background in my application, when I run it the first time, it works fine, but the second time it crashes. Please help me with this.

+4
source share
5 answers

Try to do:

 new File("loc/xyz1.mp3").renameTo(new File("loc/xyz.mp3")); 

This should automatically overwrite the original file. This answer was taken from here: How to rename an existing file

+14
source

The docs say:

Renames the file indicated by this abstract path.

Many aspects of the behavior of this method are inherently platform-dependent: the renaming operation may not be a file from one file system to another, it may not be atomic, or it may not work if a file with the target destination name already exists. You always need to check the return value to make sure that the rename operation is successful.

In AsyncTask you cannot guarantee src and dst , as @Machinarius said, check src.exists() && dst.exists() , possibly avoiding the error. Use deleteOnExit also good practice.

+1
source

In the second run, dst does not exist on the file system; you must throw an if (src.exists() && dst.exists()) in your code to avoid an error.

0
source

These two methods delete () and renameTo () will return true or false depending on the result of the execution. You probably need to add a status check if the previous step was successful and the file actually exists in the transfer path.

0
source

You must rename the file using Files , it works much more reliable than renameTo() .

 Path source = currentFile.toPath(); try { Files.move(source, source.resolveSibling(formattedName)); } catch (IOException e) { e.printStackTrace(); } 

http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#move(java.nio.file.Path , java.nio.file.Path, java.nio. file.CopyOption ...)

0
source

All Articles