Filipe Gonçalves Filipe Gonçalves - 3 months ago 6
Java Question

File already existing - repeated name

i am creating a file and when i create that file, i check if it already exists. If it already exists, i want to create it with the same name, but with the (1) after it. I am able to do that and here is the code :

File apkReceived = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/"+receivedApkName + ".apk");
if(apkReceived.exists()){
apkReceived=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/"+receivedApkName + "(1)"+".apk");
}
byte[] buffer = new byte [8192];
FileOutputStream fos=new FileOutputStream(apkReceived);


then it would continue... (i am writing things on the file).

This works but the problem is that in this situation :

FileTest.apk

FileTest(1).apk

If I receive another Filetest, it will sub my FileTest(1), since it will create it again.
A solution for this would be to check if the file exists again, but then i would have to be doing that for ever.

My goal would be to create (1) and then (2) , etc.
Does any one of you know how to do this ?

Answer

To avoid reinventing the wheel I suggest using Timestamp it hardly ever will have collisions.

java.util.Date date= new java.util.Date();
Timestamp tstamp = new Timestamp(date.getTime());
File apkReceived = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/"+receivedApkName + tstamp + ".apk");
Comments