Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Appending to File



Appending To File in Groovy

We can append to a File in Groovy using interesting ways. Following are three most popular ways to create a file in Groovy −

  • Using left shift operator

  • Using FileWriter in Append Mode.

Let's take a look at each of the way to append file in Groovy.

Append To File Using left shift (<<) Operator

We can use left shift (<<) Operator with File object to append content to a file in groovy like style.

Syntax

Following statement appends a string to a file using left shift (<<) Operator−

myFile << "This is a log entry.\n"

Following is the example to demonstrate use of left shift (<<) Operator−

Example.groovy

def logFile = new File('log.txt')
logFile << "This is a log entry.\n"
logFile << "This is another log entry.\n"

Output (Content of log.txt file)

This is a log entry.
This is another log entry.
  • The above code would create file test.txt if not present.

  • With every use of << operator, a string is appended to the end of the file.

  • To create a new line, we can use \n.

Write To File using FileWriter in Append Mode

We can use FileWriter in append mode by passing true as second argument in FileWriter constructor−

Syntax

FileWriter writer = new FileWriter(file, true) // true signifies append mode

Example: Write To File Using Files.write() Method

Following is the example to demonstrate to write a file in given directory using Files.write() method −

def file = new File('data.txt')
FileWriter writer = new FileWriter(file, true) // true signifies append mode

try {
   writer.write("First Line.\n")
   writer.write("Second Line.\n")
} finally {
   writer.close()
}

The above code would create file test.txt if not created and append lines to end of the file.

Output

First Line.
Second Line.
  • The above code would create file data.txt if not present.

  • Using FileWriter is more verbose than Groovy specific options.

  • Passing true, opens the file in append mode and close() method is required to flush the contents to file and release the resources.

Advertisements