Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Increment filename if file exists

Tags:

java

android

How to increment filename if the file already exists? Here's the code that I am using -

int num = 0;

String save = at.getText().toString() + ".jpg";

File file = new File(myDir, save); 

if (file.exists()) {
    save = at.getText().toString() + num +".jpg";

    file = new File(myDir, save); 
    num++;
}

This code works but only 2 files are saved like file.jpg and file2.jpg

like image 283
DarShan Avatar asked Dec 24 '16 14:12

DarShan


People also ask

How to Increment the filename if file already exists in java?

Calling getUniqueFileName(new File('/dir/example. txt') when 'example. txt' already exists while generate a new File targeting '/dir/example (1). txt' if that too exists it'll just keep incrementing number between the parentheses until a unique file is found, if an error happens, it'll just give the original file name.


1 Answers

This problem is always initializative num = 0 so if file exists, it save file0.jpg and not check whether file0.jpg is exists ? So, To code work. You should check until available :

int num = 0;
String save = at.getText().toString() + ".jpg";
File file = new File(myDir, save);
while(file.exists()) {
    save = at.getText().toString() + (num++) +".jpg";
    file = new File(myDir, save); 
}
like image 183
nartoan Avatar answered Oct 21 '22 10:10

nartoan