Groovy web console

subscribe to the feed Subscribe
to this
site
GString interpolating InputStreams - unexpected result (via #groovywebconsole)
tweet this snippet Tweet
this
script

GString interpolating InputStreams - unexpected result

Published 7 years ago by Dave Crane with tags GString interpolation InputStream gotcha
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
/*
I have always naively assumed that groovy's GString interpolator ${myVariable} syntax could be
interchanged with toString() pretty much, but here's an important case where it can't be. Interpolating
an InputStream will spit out the entire contents of the stream, which can have some serious consequences!

Issue described in a bit more detail here:
http://sunwheeltech.blogspot.com/2010/09/when-is-log-statement-not-just-log.html
*/
def bytes=new Byte[5];
bytes[0]='h';
bytes[1]='e';
bytes[2]='l';
bytes[3]='l';
bytes[4]='o';
def is=new ByteArrayInputStream(bytes)

println "BEFORE: bytes available - ${is.available()}"
println is.toString()
println "AFTER toString(): bytes available - ${is.available()}"
println "stream ${is}"
println "AFTER interpolation: bytes available - ${is.available()}"