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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With