Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - File Size



Groovy provides File class which provides various method to get size of a file or directory in bytes as shown in examples below −

Example - Getting file size

File.length() returns the size of the file in bytes.

Example.groovy

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

Output

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

File size: 80 bytes

Example - Getting Directory Size

File.length() result is operating system dependent in case of directories and is not reliable.

Example.groovy

def file = new File('E:/Dev/groovy')
println "Directory size: ${file.length()} bytes"

Output

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

Directory size: 0 bytes

Example - Checking Last modiification date

File.lastModified() returns the last modification time of a file, a long value as milliseconds since epoch.

Example.groovy

def file = new File('data.txt')
def lastModifiedTime = new Date(file.lastModified())
println "Last modified: ${lastModifiedTime.format('yyyy-MM-dd HH:mm:ss')}"

Output

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

Last modified: 2025-05-07 12:57:30
Advertisements