Kotlin Files Attributes and List Files/Folders in Directory

JDK8 has a Files class that provides utility methods to list all files and folders in a directory and list attributes of a file.

import java.nio.file.Files
import java.nio.file.Paths
import java.util.stream.Collectors

fun main(args : Array<String>){
    //Create a Path object
    val path = Paths.get(if(args.isEmpty()){
        System.getProperty("user.dir")
    } else {
        args[0]
    })

    //Check if the Path is a directory
    if (Files.isDirectory(path)){
        //List all items in the directory. Note that we are using Java 8 streaming API to group the entries by
        //directory and files
        val fileDirMap = Files.list(path).collect(Collectors.partitioningBy( {it -> Files.isDirectory(it)}))

        println("Directories")
        //Print out all of the directories
        fileDirMap[true]?.forEach { it -> println(it.fileName) }

        println("\nFiles")
        println("%-20s\tRead\tWrite\tExecute".format("Name"))
        //Print out all files and attributes
        fileDirMap[false]?.forEach( {it ->
            println("%-20s\t%-5b\t%-5b\t%b".format(
                    it.fileName,
                    Files.isReadable(it), //Read attribute
                    Files.isWritable(it), //Write attribute
                    Files.isExecutable(it))) //Execute attribute
        })
    } else {
        println("Enter a directory")
    }
}

Output

Directories
target
.idea
src

Files
Name                	Read	Write	Execute
belchers.txt        	true 	true 	false
belchers.burgers    	true 	true 	false
pom.xml             	true 	true 	false
bob.ser             	true 	true 	false
OCJAP.iml           	true 	true 	false
bob.csv             	true 	true 	false
data.burgers        	true 	true 	false

Explanation

The program begins by testing for command line arguments. If a command line argument is available, the command line argument is used for the Path. Otherwise, we use the current working directory. The result is passed to Paths.get() and a Path object is returned.

Line 14 checks if the Path is a directory by using Files.isDirectory(). If true, the program proceeds to line 17 otherwise exits with an error message. Line 17 obtains a map of all directories and files in the path. We use the Files.list() method which returns a Java 8 Stream object. The next part transforms the Stream into a Map<Boolean, List> by using Collectors.partioningBy(). In our case, we are patitioning by true or false.

We pass the it variable (which is a Path object), to Files.isDirectory(). When the result is true, all Paths are grouped with the true key on the resulting map. All false results are grouped into a list and placed into the false key in the resulting map. When the operation is complete, we will have all files and directories sorted.

Line 21 prints out all directories in the folder. In our case, we are simply using forEach() to print out all of the directories. For demonstration purposes, we include additional information with each of the files. Lines 26-32 prints out the file name, read attribute, write attribute, and executable attribute.

The file name is obtained from the fileName property on the Path (line 28). Next we test if the file is readable by using the Files.isReadable() method (line 29. The Files class also has isWritable and isExecutable which work the same as isReadable (lines 30, 31 respectively). All methods return either true or false.

Methods Used

isDirectory(path : Path) : Boolean

Returns true when the Path object points at a directory, otherwise false.

val dir = Files.isDirectory(Paths.get(System.getProperty("user.dir")))

list(dir : Path) : Stream

Returns a Java 8 Stream object of type Path. All of the elements of the stream are lazily populated and contain the entries in a directory.

Files.list(Paths.get(System.getProperty("user.dir"))).forEach{it -> println(it.name) })

isReadable(path : Path) : Boolean

True when the file is readable, otherwise false.

val r = Files.isReadable(Paths.get(System.getProperty("user.dir")))

isWritable(path : Path) : Boolean

True when the file is writable

val w = Files.isWritable(Paths.get(System.getProperty("user.dir")))

isExecutable(path : Path) : Boolean

Tre when the file is an executable.

val e = Files.isExecutable(Paths.get(System.getProperty("user.dir")))

References

https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s