Home > Net >  Add suffix to filename if file exists in internal storage
Add suffix to filename if file exists in internal storage

Time:09-22

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()

CodePudding user response:

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

CodePudding user response:

Updated answer :

fun main() {
    val fileName = "filename.ext"
    val file = File(fileName)
    file.mkdirs()
    if (file.exists()) {
        val extension = file.extension
        var newFileName = fileName
        for (i in 1..Int.MAX_VALUE) {
            newFileName = file.nameWithoutExtension.plus("($i).").plus(extension)
            if (!File(newFileName).exists())
                break
        }
        println(newFileName)
        file.renameTo(File(newFileName))
        file.createNewFile()
    }
}

CodePudding user response:

You can use the timestamp.

String timeStamp = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
String fileName = "filename_"   timeStamp;
File imageFile = File.createTempFile(fileName, "jpg", getFilesDir());
  • Related