如果文件存在,如何增加文件名 [英] How to Increment filename if file exists

查看:74
本文介绍了如果文件存在,如何增加文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果文件已经存在,如何增加文件名?这是我正在使用的代码-

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

这篇关于如果文件存在,如何增加文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆