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.

  1. To replace the full text of the file content with a String you can use the setText extension method of the java.io.File (or just Groovy's syntax for property assignment): ...

Get Groovy 2 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.