Kotlin Files.delete()

The java.nio.file.Files class has a delete() method that accepts a Path object and deletes the item from the file system. Here is an example Kotlin program that demonstrates deleting a file.

package ch9.files

import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths

/**
 * Wraps Files.exists
 */
private fun Path.exists() : Boolean = Files.exists(this)

/**
 * Wraps Files.isDirectory
 */
private fun Path.isFile() : Boolean = !Files.isDirectory(this)

/**
 * Delete a Path object
 */
private fun Path.delete() : Boolean {
    return if(isFile() && exists()){
        //Actual delete operation
        Files.delete(this)
        true
    } else {
        false
    }
}

fun main(args : Array<String>){
    if(args.isNotEmpty()){
        args.forEach { it ->
            val p = Paths.get(it)

            if(p.delete()){
                println("Deleted ${p.fileName}")
            } else {
                println("Could not delete ${p.fileName}")
            }
        }
    } else {
        println("One or more file paths required")
    }
}

Explanation

The example program only deletes files, but the delete method can also be used on empty directories. We also need to test if the path exists otherwise a NoSuchFileException will get thrown. (Note: Use deleteIfExists() to suppress the exception if desired).

Given the fact that we only want to delete existing files, we use two extension files to help with the goal. The first function is on line 10, Path.exists(). The extension function simply wraps Files.exists so that we can call exists() directly on the Path object, Likewise, we have an Path.isFile() (line 15) extension function that wraps Files.isDirectory.

Our final extension function, Path.delete() is found on lines 20-28 and contains the call to Files.delete(). The function returns true when deleting the file is successful, otherwise false. The main method uses the Path.delete() function to delete the file and reports back to the user the outcome of the operation.

References

https://docs.oracle.com/javase/8/docs/api/?java/io/File.html

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: