关于重名文件重命名的问题

目标


当文件夹中的文件出现重名时,我们需要在新建的文件名称后面加上1, 2, 3;
例如:
一个文件夹中有文件 test.txt 后,再向该文件加中加入同名文件,文件名依次默认变为 test1.txt, test2.txt, test3.txt, …

实现


[java code]
public class Main {
    //定义目录路径
    public static final String PATH = "F://JavaTest";
    //创建不同名的新文件
    public static void createFile(String filename) {
        //注意 . 的分隔方式
        String[] args = filename.split("\\.");
        int count = 1;
        File file = new File(PATH, filename);
        while (file.exists()) {
            filename = args[0] + count + "." + args[1];
            file = new File(PATH, filename);
            count ++;
        }
        try{
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String args[]) {
        for (int i = 0; i < 10; i++) {
            Main.createFile("test.txt");
        }
    }
}

总结


勤于思考,善于总结,乐于分享。

你可能感兴趣的:(关于重名文件重命名的问题)