Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Groovy - File Input/Output

12. File Input/Output

File I/O is essential for reading data from and writing data to files in Groovy. It allows you to interact with external files, such as text files, CSV files, JSON files, and more. Groovy provides convenient ways to perform file I/O operations.

Reading from a File:

To read data from a file in Groovy, you can use the 'File' class, which provides various methods for reading file contents.

Example: Reading a Text File
def file = new File("example.txt")
if (file.exists()) {
    def text = file.text
    println("File Contents:\n$text")
} else {
    println("File does not exist.")
}
 

In this example, we check if the file "example.txt" exists, and if it does, we read its contents using the 'text'property.

Reading Line by Line:

You can also read a file line by line using the 'eachLine' method.

Example: Reading a File Line by Line
def file = new File("example.txt")
if (file.exists()) {
    file.eachLine { line ->
        println("Line: $line")
    }
} else {
    println("File does not exist.")
}
 

This code reads each line from "example.txt" and prints it.

Writing to a File:

To write data to a file, you can use the 'text' property or the 'withWriter' method.

Example: Writing to a Text File
def data = "This is some sample text to write to a file."
def file = new File("output.txt")
file.text = data
 

In this example, we write the content of the 'data'variable to the file "output.txt" using the 'text' property.

Appending to a File:

You can append data to an existing file using the 'leftShift' operator ('<<') or the 'withWriter' method with the 'append' flag.

Example: Appending to a File
def newData = "Additional data to append."
def file = new File("output.txt")
file << newData // Append using leftShift operator
file.withWriter(append: true) { writer ->
    writer.writeLine(newData) // Append using withWriter method
}
 

These examples append the 'newData' to the file "output.txt."

Working with Binary Files:

For binary file I/O, you can use the 'withInputStream' and 'withOutputStream'methods to read and write binary data.

Example: Reading and Writing Binary Files
def inputFilePath = "input.bin"
def outputFilePath = "output.bin"

// Writing binary data
def dataToWrite = [0x48, 0x65, 0x6C, 0x6C, 0x6F] // "Hello" in ASCII
def outputFile = new File(outputFilePath)
outputFile.withOutputStream { outputStream ->
    dataToWrite.each { byteValue ->
        outputStream.write(byteValue)
    }
}

// Reading binary data
def inputFile = new File(inputFilePath)
if (inputFile.exists()) {
    def bytesRead = []
    inputFile.withInputStream { inputStream ->
        while (true) {
            def byte = inputStream.read()
            if (byte == -1) break // End of file
            bytesRead.add(byte)
        }
    }
    println("Read binary data: ${bytesRead.collect { String.format("%02X", it) }.join()}")
} else {
    println("Input file does not exist.")
}
 

In this example, we write binary data to "output.bin" and then read it back from "input.bin."

Handling File Exceptions:

When working with files, it's important to handle potential exceptions, such as 'FileNotFoundException'or 'IOException'.

Example: Handling File Exceptions
def filePath = "nonexistent.txt"
try {
    def file = new File(filePath)
    def text = file.text
    println("File Contents:\n$text")
} catch (FileNotFoundException e) {
    println("File not found: ${e.message}")
} catch (IOException e) {
    println("IOException: ${e.message}")
}
 

In this example, we handle the 'FileNotFoundException' and'IOException' exceptions that might occur when working with files.

Conclusion:

File I/O operations are essential for reading and writing data from and to files in Groovy. Understanding how to read, write, append, and handle exceptions when working with files is crucial for developing applications that need to interact with external data sources. Groovy's built-in support for file I/O makes these operations relatively straightforward to implement.