Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - File Properties



Groovy provides File class which provides multiple properties and method to access a File Characteristics. In this chapter, we'll explore them by examples.

Example - Getting name of a file

File.name returns the name of the file/directory without parent path.

Example.groovy

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

Output

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

File name: data.txt

Example - Getting full path of a file

File.path returns the full path of the file/directory.

Example.groovy

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

Output

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

File path: data.txt

Example - Getting absolute path of a file

File.absolutePath returns the absolute path of the file/directory.

Example.groovy

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

Output

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

File path: E:\Dev\groovy\data.txt

Example - Getting path of parent of a file

File.parent returns the path of the parent of the file or directory. In case of root directory, it will return null.

Example.groovy

def file = new File('data.txt')
println "Parent path: ${file.parent}"

Output

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

Parent path: null

Example - Getting path of parent of a file

File.parent returns the path of the parent of the file or directory. In case of root directory, it will return null.

Example.groovy

def file = new File('data.txt')
println "Parent path: ${file.parent}"

Output

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

Parent path: null

Example - Getting parent of a file as File Object

File.parentFile returns the parent of the file or directory as File Object. In case of root directory, it will return null.

Example.groovy

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

Output

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

Parent: null
Advertisements