3

In Java, I can easily use following code, to write a ByteArrayOutputStream to a file. However, try-with-resources doesn't work in Groovy :(

ByteArrayOutputStream byteArrayOutputStream = getByteStreamMethod();
try(OutputStream outputStream = new FileOutputStream("thefilename")) {
    byteArrayOutputStream.writeTo(outputStream);
}

I have been trying to follow links like http://mrhaki.blogspot.co.uk/2009/11/groovy-goodness-readers-and-writers.html and SO answer here IntelliJ error - java: try-with-resources is not supported in -source 1.6 error. Even though in project settings 1.7 JDK is selected

but I am not able to think of Groovy syntax, to write above java code block as. Could you please do a little handholding here as to how to write above java code block in Groovy?

PS: I am using Groovy v2.4.12

Vishal
  • 666
  • 1
  • 8
  • 30

3 Answers3

5

Groovy's alternatives for are methods like:

  • .withClosable(Closure cl)
  • .withOutputStream(Closure cl)

In your case following example would write data from ByteArrayOutputStream to a given File:

final ByteArrayOutputStream os = new ByteArrayOutputStream()
os.withCloseable {
    it << "Lorem ipsum dolor sit amet".bytes
}

new File("/tmp/lorem.txt").withOutputStream { stream ->
    os.writeTo(stream)
}

println new File("/tmp/lorem.txt").text

In the last line we are printing current content of /tmp/lorem.txt file:

Lorem ipsum dolor sit amet

Hope it helps.

Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131
2

in groovy for in/out streams there is an extension method withStream(Closure) :

Passes this Stream to the closure, ensuring that the stream is closed after the closure returns, regardless of errors.

So, your java code could look like this:

ByteArrayOutputStream byteArrayOutputStream = getByteStreamMethod();
new FileOutputStream("thefilename").withStream{outputStream->
    byteArrayOutputStream.writeTo(outputStream);
}
daggett
  • 26,404
  • 3
  • 40
  • 56
0

Another way is:

void saveToFile(ByteArrayOutputStream os, File output) {
    output.bytes = os.toByteArray()
}

Although I guess that it is not the best way when handling large size files as the stream will first be converted into bytes before saving.

lepe
  • 24,677
  • 9
  • 99
  • 108