Add suffix to filename if file exists in internal storage

Issue

I want to add a suffix to the filename, which counts up.

val file  File(it.path)

If the file already exists i need to add a suffix to the filename: filename(1).ext, filename(2).ext.. counting upwards.

I tried renaming the file, but it adds the suffix after the file extension: filename.ext(1)

      file.mkdirs()
      if (file.exists()) {
        file.renameTo(File(it.path+"(1)"))
      }

      file.createNewFile()

Solution

Let’s consider possible cases:

 1. "standard" case, filename with extension: abc.jpg -> abc(1).jpg
 2. no extension: abc -> abc(1)
 3. double extension, like tar.gz: -> abc.tar.gz -> abc(1).tar.gz

So, in all cases, we want to append suffix before the first dot occurrence OR if there is no extension at the end of a file.

fun appendSuffix(filename: String, suffix: String): String {
    return if (filename.contains('.')) {
        // has ext, the easiest way is to replace a first dot :)
        filename.replaceFirst(".", "$suffix.")
    } else {
        // no ext
        filename + suffix
    }
}

and some tests:

fun main() {
    println(appendSuffix("abc", "(1)"))
    println(appendSuffix("abc.jpg", "(1)"))
    println(appendSuffix("abc.tar.gz", "(1)"))
}

// output:
abc(1)
abc(1).jpg
abc(1).tar.gz

How to use it? I assume you know how to get the filename :). If you need check if it should be “(1)” or “(2)” you can make simply loop, where you:

  1. check if filename exists
  2. append “(n+1)”
  3. go back to 1

Answered By – Cililing

Leave a Comment