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
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.
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);
}
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