如果文件存在,如何增加文件名
问题描述:
如果文件已经存在,如何增加文件名?这是我正在使用的代码-
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++;
}
此代码有效,但仅保存了2个文件,如file.jpg和file2.jpg
This code works but only 2 files are saved like file.jpg and file2.jpg
答
此问题始终是初始化 num = 0
,因此,如果 file
存在,则会保存 file0.jpg
而不检查 file0.jpg
是否存在?因此,要进行编码工作.您应该检查直到可用:
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);
}