androidkotlinfileduplicatesandroid-jetpack-compose

How Do You Add An Incrementing Number To The End Of A Duplicate File Name In Kotlin?


I'm trying to develop a feature that adds a number to the end of a file that has the same name as another file in Kotlin. The number will increment for each file of the same name. This is important because all files with the same name will be automatically deleted except for the first one with that name.

I've developed a feature that partially achieves what I want but doesn't work past more than two files.

Here is the code for that feature

// In The Main Activity Of A Jetpack Compose Project In Android Studio

// Directory
val directory = File(this.filesDir, "Directory")
directory.mkdir()

// List Of Files In Directory
var fileList by mutableStateOf<List<File>>(directory.listFiles()?.toList() ?: listOf())

// File Name
val fileName = "File Name"

// Number That Goes On The End Of Duplicate Files
val counter by remember{mutableStateOf(1)}

// Function To Create File
fun createFile() {

    // Conditional That Adds Number To File Name
    val _fileName = "${fileName}${if (directory.any { it.name == fileName }) " ${counter + 1}" else ""}"  

    // File
    val file = File(directory, fileName)

    // Recompose File List
    fileList = directory.listFiles()?.toList() ?: listOf()
}

// Layout
Column(
   modifier.fillMaxSize
) {

  // Button To Add File
  Button(onClick{ createFile }) { Text(text = "Add File") }

  // Displayed List Of Files
  fileList.forEach{ file ->
   
     // Displayed File Name
     Text(text = file.name)

   }
}

Any file after the second one is automatically deleted. How do I fix this? Thanks.


Solution

  • I would try to put all the logic in ViewModel (for testing) and as it seems to me, because of the need to create a file on the first access and add a number for subsequent ones, you can do it this way:

    fun createFile(fileName: String, directory: File) {
        val dirFiles = directory.listFiles()?.associateBy(File::getName) ?: emptyMap()
        var newFileName = fileName
        var counter = 1
        while (dirFiles[newFileName] != null) {
            newFileName = "$fileName ${counter++}"
        }
        val newFile = File(directory, newFileName)
        ...
    }