Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - File Permissions



Reading file permissions is an important steps while dealing with files. Groovy provides easy way to check if a file is readable, writable or executable using File object methods as shown in examples below−

Example - Checking if file is readable

File.canRead() returns the true in case file is readable and can be read by Groovy based application. This is platform dependent operation.

Example.groovy

def file = new File('data.txt')
println "File can be read: ${file.canRead()}"

Output

When we run the above program, we will get the following result.

File can be read: true

Example - Checking if file is writable

File.canWrite() returns the true in case file is writable and can be written by Groovy based application. This is platform dependent operation as well.

Example.groovy

def file = new File('data.txt')
println "File can be written: ${file.canWrite()}"

Output

When we run the above program, we will get the following result.

File can be written: true

Example - Checking if file is executable

File.canExecute() returns the true in case file is executable. This is platform dependent operation as well.

Example.groovy

def file = new File('data.txt')
println "File is executable: ${file.canExecute()}"

Output

When we run the above program, we will get the following result.

File is executable: true

Example - Getting Path Object from a File

File.toPath() returns the java.nio.file.Path object which is representing the current file. This Path object can be used to perform multiple modern file operations.

Example.groovy

def file = new File('data.txt')
println "Path: ${file.toPath()}"

Output

When we run the above program, we will get the following result.

Path: data.txt
Advertisements