java文件重新创建问题

java判断如果存在该文件就改名新建一个文件 如:
File file=new File("f:/test/C.txt");
如果该目录已经有了该文件就新建一个C2.txt文件;
如果已经有了c2.txt就新建一个c3.txt 如此判断循环
怎么写啊 求大神

String dn = "c";
String ext = "txt";
int i = 0;
File file=new File("f:/test/" + fn + "." + ext);
while (file.exists())
{
file=new File("f:/test/" + fn + i + "." + ext);
}
做你的操作

 笔误


String dn = "c";
String ext = "txt";
int i = 0;
File file=new File("f:/test/" + fn + "." + ext);
while (file.exists())
{
file=new File("f:/test/" + fn + (++i) + "." + ext);
}
//做你的操作
...

建议使用 commons-io 包中的FileUtils类,里面都是各种封装的文件操作的。按照行读取,返回数组,判断是否存在等等。可以参考这个帖子,都是封装好的,用起来方便,比你自己写的io稳定。
https://blog.csdn.net/houfeng30920/article/details/51997368

File file=new File("f:/test/C"+System.currentTimeMillis()+".txt");
文件名加上时间戳,不会重复

//亲测可行
package test.file;
import java.io.File;
import java.io.IOException;

public class TestFile {

public static void main(String[] args) {
    int i = 0;      
    String path="D:/test/";
    File file=new File(path);
    if(!file.exists()){
        file.mkdirs();}     
    file = new File(path,"c"+(++i) + "." + "txt");
    while(file.exists()){
        file = new File(path,"c"+(++i) + "." + "txt");
    }
    try {
        file.createNewFile();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}