
Groovy 2 Cookbook

Searching and replacing file content is an often needed routine that can be automated with the help of Groovy scripts, one of which will be shown in this recipe.
Let's assume that we have an input.txt
file that contains some tabulation characters. We want to replace the tabulation characters with spaces and save the results into a output.txt
file.
To perform any action on these files (similar to the Filtering a text file's content recipe), we need to create two instances of java.io.File
objects:
def inputFile = new File('input.txt') def outputFile = new File('output.txt')
Let's go through several ways to achieve the desired result:
First of all, we will take advantage of the transformLine
method available in the java.io.Reader
class, as well as the withWriter
and withReader
methods that are described in more detail in the Writing to a file and Reading from a file recipes:
outputFile.withWriter { Writer writer -> inputFile...
Change the font size
Change margin width
Change background colour