Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename an existing file?

Tags:

java

file

android

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 while delete src file. How can I accomplish this ? I was trying ,

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

I am running this in AsyncTask in background in my app , when I execute it first time , it works perfectly , however second time , it crashes. Please help how should I go about this.

like image 915
h4ck3d Avatar asked Dec 03 '22 00:12

h4ck3d


2 Answers

Try doing:

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

like image 106
Barney Avatar answered Dec 23 '22 18:12

Barney


Docs says:

Renames the file denoted by this abstract pathname.

Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a 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. The return value should always be checked to make sure that the rename operation was successful.

In AsyncTask, you can not guarantee the src and dst ,as @Machinarius said, check src.exists() && dst.exists() maybe avoid you error. Use deleteOnExit also a good practice.

like image 31
lichengwu Avatar answered Dec 23 '22 16:12

lichengwu