1. Overview

Renaming files is a common task in Kotlin development. In this guide, we’ll explore two techniques and best practices for renaming files.

2. Using Kotlin’s File Class

Kotlin provides a rich set of functionalities for file manipulation. It provides a straightforward way to rename files. We can achieve file renaming using the renameTo() method provided by the File class. This method takes as an argument the full path of the new file. Here’s a basic example:

@Test
fun `when using renameTo, then file is renamed`() {
    val oldFilePath = Paths.get("src/test/resources/oldFile.txt")
    val newFilePath = Paths.get("src/test/resources/newFile.txt")

    val oldFile = oldFilePath.toFile()
    oldFile.writeText("Hello Kotlin")

    val newFile = newFilePath.toFile()

    if (oldFile.renameTo(newFile)) {
        assertThat(newFile.exists()).isTrue()
    } else {
        fail("Failed to rename file.")
    }

    //cleanup
    newFile.delete()
}

This approach is suitable for basic file renaming operations where we have full control over file paths. First, we created an oldFile.txt with some basic content. Then, we call the renameTo() method to rename it. Moreover, we assume that the source file exists and the destination file doesn’t exist. There are no additional checks implemented.

Additionally, at the end of our example, we do a cleanup by deleting the new file.

3. Using the move() Method

In addition to the traditional file manipulation methods available in Kotlin, we can also take advantage of the Files class provided by the Java NIO package. The move() method offers a more modern and robust approach to file manipulation, including renaming files. This method allows us to move or rename a file atomically. In other words, the operation either completes entirely or fails without leaving the file system in an inconsistent state.

Here’s how we can use it:

@Test
fun `when using move, then file is renamed`() {
    val oldFilePath = Paths.get("src/test/resources/oldFile.txt")
    val newFilePath = Paths.get("src/test/resources/newFile.txt")

    val oldFile = oldFilePath.toFile()
    oldFile.writeText("Hello Kotlin")

    Files.move(oldFilePath, newFilePath, StandardCopyOption.REPLACE_EXISTING)
    val newFile = newFilePath.toFile()
    assertThat(newFile.exists()).isTrue()

    //cleanup
    newFile.delete()
}

In the example, we created an oldFile.txt file in the resource directory. Then, with the move() method, we renamed the file to newFile.txt. Additionally, with the parameter REPLACE_EXISTING, we configured to replace the file in case it exists in the destination path.

4. Handling Edge Cases

When renaming files, it’s essential to consider potential edge cases and handle them gracefully. These include scenarios such as file existence checks. Here’s an example demonstrating how to handle file existence checks before renaming:

@Test
fun `when renaming, checks on files succeed`() {
    val oldFilePath = Paths.get("src/test/resources/oldFile.txt")
    val newFilePath = Paths.get("src/test/resources/newFile.txt")

    val oldFile = oldFilePath.toFile()
    oldFile.writeText("Hello Kotlin")

    val newFile = newFilePath.toFile()

    if (oldFile.exists()) {
        if (newFile.exists()) {
            fail("A file with the new name already exists.")
        } else {
            if (oldFile.renameTo(newFile)) {
                assertThat(newFile.exists()).isTrue()
            } else {
                fail("Fail rename failed")
            }
        }
    } else {
        fail("The old file does not exist.")
    }

    //cleanup
    newFile.delete()
}

First, we check if the original file exists before renaming. We do it with oldFile.exists(). Then, we check if the destination file exists by calling newFile.exists(). Finally, we verify if the renameTo() succeeded. We call fail() in case the condition returns unexpected results. By incorporating such checks, we can ensure smooth file renaming operations without encountering unexpected errors.

5. Conclusion

Renaming files in Kotlin is a straightforward process. We can use the built-in method exposed by the File class or use the Files class from the Java NIO package. The first method is very straightforward. On the other hand, Files.move() simplifies error handling and ensures that file renaming operations are executed reliably.

As always, the source code of the examples is available over on GitHub.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.