Writing to a file
Java's I/O API demands a lot of "ceremony code" to cover the file output operations (and actually any other I/O resource). Groovy adds several extensions and syntax sugar to hide Java's complexity and make the code more concise than its Java counterpart. In this recipe, we will cover the file writing methods that are available in Groovy.
Getting ready
To start writing to a file, you just need to create an instance of java.io.File
, for example:
File file = new File('output.txt')
How to do it...
Now let's see which writing operations we can perform on a File
object.
To replace the full text of the file content with a
String
you can use thesetText
extension method of thejava.io.File
(or just Groovy's syntax for property assignment):file.text = 'Just a text'
This also gives you the possibility of assigning multiple text lines at once:
file.text = '''What's in a name? That which we call a rose By any other name would smell as sweet.'''
You can also assign binary content with the help...