如何创建新文件名而不是覆盖 Groovy 中的文件

How to create a new file name instead of overwriting a file in Groovy

我将文件移动到文件夹。有没有办法不覆盖具有该名称的文件?

例如,folder 包含一个名为:file1.pdf 的文件。如何将另一个名为 file1.pdf 的文件移动到该文件夹​​中,以便将名称更改为例如file1-1.pdf, file1-2.pdf 以防止原始文件被覆盖。

我正在使用子字符串来执行此操作,但它的代码又长又糟糕。

你可以使用这样的东西:

def save = { File dir, String name ->
    int version = 1
    def splitName = name.split(/\./, 0).with { it -> it.length == 1 ? [it[0], ''] : [it[0..-2].join('.'), ".${it[-1]}"] }
    def rename = { String prefix, String ext -> "$prefix-$version$ext" }

    while (new File(dir, name).exists()) {
        name = rename(*splitName)
        version++
    }
    println "Save the file as $name"
}

save(new File('/tmp'), 'file.txt')

假设您已经有一个文件 /tmp/file.txt 和一个文件 /tmp/file-1.txt,打印出:Save the file as file-2.txt