Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 6 Next »

Groovy provides a number of
helper methods for working with IO. All of these work with standard Java Reader/Writer and InputStream/OutputStream and File and URL classes.
The use of closures allows resources to be processed ensuring that things are properly closed irrespective of exceptions. e.g. to iterate through each line of a file the following can be used...

Error rendering macro 'code': Invalid value specified for parameter 'lang'
new File("foo.txt").eachLine { line -> doSomething(line) }

If for whatever reason the doSomething() method were to throw an exception, the eachLine() method ensures that the file resource is correctly closed. Similarly if an exception occurs while reading, the resource will be closed too.

If you wish to use a reader/writer object or an input/output stream object there are helper methods to handle the resource for you via a closure - which will automatically close down any resource if an exception occurs. e.g.

Error rendering macro 'code': Invalid value specified for parameter 'lang'
new File("foo.txt").withReader { reader ->
	while (true) {
		def line = reader.readLine()
	}
}

Using processes

Groovy provides a simple way to execute command line processes.

Error rendering macro 'code': Invalid value specified for parameter 'lang'
def process = "ls -l".execute()
println "Found text ${process.text}"

The expression returns a java.lang.Process instance which can have the in/out/err streams processed along with the exit value inspected etc.

e.g.

Error rendering macro 'code': Invalid value specified for parameter 'lang'
def process = "ls -l".execute()
process.in.eachLine { line -> println line }
  • No labels