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

PressRex profile image
by PressRex
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}" 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.

Source: View source

PressRex profile image
by PressRex

Subscribe to New Posts

Lorem ultrices malesuada sapien amet pulvinar quis. Feugiat etiam ullamcorper pharetra vitae nibh enim vel.

Success! Now Check Your Email

To complete Subscribe, click the confirmation link in your inbox. If it doesn’t arrive within 3 minutes, check your spam folder.

Ok, Thanks

Read More