如果文件名存在,则创建并增加文件名 [英] Create and increment file name if the name exists

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

问题描述

我有一个存储测试题的文件.

I have a file that stores Test questions.

"Test.ser"

我希望能够以相同的名称创建文件,但每次有人进行测验以存储答案时都添加一些增量或追加.

I want to be able to create files with the same name but with some incrementor appended for each time someone takes the Test to store the Answers.

"Test1.ser"
"Test2.ser"
   ...

但是,我想不出一种实现此方法的方法.计数器可以工作,但是如果有人重新运行该程序,计数器将重置.

However, I can't think of a way to implement this. A counter could work, but the counter would reset if someone re-ran the program.

有人知道这怎么可能吗?非常感谢!

Does anyone have an idea how this is possible? Thanks a lot!

int count = 1;
while (searching) {
    fileName = survey.name + Integer.toString(count) + ".ser";
    f = new File(fileName);

    if(f.exists()) {
        count++;
    } else {
        searching = false;
    }
} // Proceed to use file name

无法获取,它超过了file_name1.ser

Can't get it it increment past file_name1.ser

推荐答案

我建议您使用

I suggest you use String.format(String, Object...), File.exists() and something like

public static void main(String[] args) {
    String fmt = "Test%02d.ser";
    File f = null;
    for (int i = 1; i < 100; i++) {
        f = new File(String.format(fmt, i));
        if (!f.exists()) {
            break;
        }
    }
    try {
        System.out.println(f.getCanonicalPath());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

修改

正如评论中指出的那样,此操作仅重试100次.如果您想支持100次以上的重试,则可以编写for循环,如

As pointed out in the comments, this only retries 100 times. If you want to support more then 100 retries you could write the for loop like,

for (int i = 1;; i++) 

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

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