Preface:
Hardly any script (let alone whole applications) can do without file access and other input/output-related issues. The JDK addresses this need with its java.io and java.netpackages. It provides elaborate support with the File and URL classes and numerous versions of streams, readers, and writers.
However, the programmer is left with the repetitive, tedious, and error-prone task of managing I/O resources, such as properly closing an opened file even if exceptions occur while processing. This is where the GDK steps in and provides numerous methods that let you focus on the task at hand rather than thinking about I/O boilerplate code. This results in faster development, better readability of your code, and more stable solutions, because resource leaks are less likely with centralized error-handling. Having read chapter 5, you may correctly surmise that this is a job for closures.
In table 9.3 (If the target is File, Iterator over lines), you saw that File objects work with Object’s iteration methods. Listing 9.4 uses this approach to print itself to the console: The output is exactly what you see as listing 9.4. Assertions are used to show the use of any , findAll, and grep. Note that file.grep{it} returns only non-empty lines, because empty strings evaluate to false.
- Listing 9.4 File’s object iteration method examples
Additionally, the GDK defines numerous methods with overloaded variants on
File, URL, Reader, Writer, InputStream, and OutputStream. We will present detailed explanations and examples for at least one variant of every important or commonly used method. The usage of the remaining methods/variants is analogous.
Traversing the filesystem:
Groovy follows the Java approach of using the File class for both files and directories, where a File object represents a location (not content, contrary to a common misconception). Using a File object from Groovy often includes calling its JDK methods in a property-style manner. For example, to display information about the current directory, you can use:
Listing 9.5 shows this in conjunction with the GDK methods
eachDir , eachFile, eachFileMatch, and eachFileRecurse. They all work with a closure that gets a File object passed into it, disregarding the filesystem entries that represent the current and parent dir (“.” and “..”). Whereas eachFile yields File objects that may represent files or directories, eachDir yields only the latter.
- Listing 9.5 File methods for traversing the filesystem
Reading from input sources:
Suppose we have a file example.txt in the data directory below our current one. It contains:
One of the most common operations with such small text files is to read them at once into a single string. Doing so and printing the contents to the console is as easy as calling the file’s text property (
similar to the getText method):
What’s particularly nice about the text property is that it is available not only on
File, but also on Reader, InputStream , and even URL. Where applicable, you can pass aCharset to the getText method. See the API documentation of java.nio.charset.Charset for details of how to obtain a reference to a Charset.
BY THE WAY
Listing 9.6 goes through some examples of file reading with more fine-grained control. The readLines method returns a list of strings, each representing one line in the input source with newline characters chopped.
- Listing 9.6 File-reading examples
The
eachLine method works on files exactly like the iteration method each does. The method is also available on Reader , InputStream, and URL . Input sources can be read a byte at a time with eachByte, where an object of type java.lang.Byte gets passed into the closure.
When the input source is made of formatted lines, splitEachLine can be handy. For every line, it yields a list of items to its closure determined by splitting the line with the given regular expression. Generally, the with<Resource> methods pass the <Resource> into the closure, handling resource management appropriately. So do the methodswithReader and withInputStream. The readLine method can then be used on such a given Reader or InputStream.
Writing to output destinations:
Listing 9.7 uses the corresponding methods for writing to an output destination. Writing a whole file at once can be achieved with File ’s write method; appending is done with append . The with<Resource> methods work exactly as you would expect. The use of withWriter and withWriterAppend is shown in the listing; withPrintWriter andwithOutputStream are analogous. The leftshift operator on File has the meaning of append.
- Listing 9.7 File-writing examples
The example file in listing 9.7 has been opened and closed seven times: five times for writing, two times for reading. You see no error-handling code for properly closing the file in case of exceptions. File ’s GDK methods handle that on our behalf. Note the use of the
writeLine and << leftshift methods. Other classes that are enhanced by the GDK with the leftshift operator with the exact same meaning are Process and Socket.
The leftshift operator on Writer objects is a clever beast. It relays to Writer’s write method, which in the GDK makes a best effort to write the argument. The idea is to write a string representation with special support for arrays, maps, and collections. For general objects, toString is used.
If the argument is of type InputStream or Reader, its content is pumped into the writer. Listing 9.8 shows this in action.
- Listing 9.8 Using Writer’s smart leftshift operator
Note that connecting a reader with a writer is as simple as:
It may seem like magic, but it is a straightforward application of operator overriding done by the GDK.
Finally, the leftshift operator on Writer objects has special support for arguments of type Writable. In general, a Writable is an object with a writeTo method: It knows how to write something. This makes a Writable applicable to:
The
Writable interface is newly introduced by the GDK and used with Groovy’s template engines, as you will see in section 9.4. It is also used with filtering, as shown in the next section.
Filters and conversions:
There are times when ready-made resource handling as implemented by the with<Resource> methods is not what you want. This is when you can use the methodsnewReader , newInputStream , newOutputStream , newWriter , and newPrintWriter to convert from a File object to the type of resource you need.
Two other conversions of this kind are from String and StringBuffer to their respective Writer s via:
A second kind of conversion is transformation of the content, either character by
character or line by line. Listing 9.9 shows how you can use transformChar and transformLine for this task. They both take a closure argument that determines the transformation result. Whatever that closure returns gets written to the writer argument.
- Listing 9.9 Transforming and filtering examples
Note that the last example of
filterLine at (1) doesn’t take a writer argument but returns a Writable that is then written to the writer with the leftshift operator.
NOTE.
Finally, a frequently used conversion is from binary data to strings with base-64 encoding, where binary data is represented only in printable characters, as specified inRFC 2045. This can be useful for sending binary coded data in an email, for example. The name of this codec comes from it having 64 symbols in its “alphabet”, 7 just as the decimal system is base 10 (10 symbols: 0–9) and binary is base 2 (2 symbols: 0 and 1):
An interesting feature of the
.html#encodeBase64()]encodeBase64 method is that it returns a Writable and can thus be used with writers, whereas the returned object also implements toString conveniently. This has saved us the work of pushing the Writable into a StringWriter.
Base-64 encoding works with arbitrary binary data with no meaning attached to it. In order to encode objects instead, we need to venture into the world of serialization, which is the topic of the next section.
Streaming serialized objects:
Java comes with a serialization protocol that allows objects of type Serializable to be stored in a format so that they can be restored in VM instances that are disconnected in either space or time. Serialized objects can be written to ObjectOutputStreams and read from ObjectInputStreams. These streams allow making deep copies of objects, sending objects across networks, and storing objects in files or databases.
Listing 9.10 shows the special GDK support for reading serialized objects from a file. First, an Integer , a String , and a Date are written to a file. They are then restored with File’s new eachObject method. A final assertion checks whether the restored objects are equal to the original.
- Listing 9.10 Reading serialized objects from files
As a variant,
can be written as:
Supplement:
* Documentation > User Guide > Input Output
* Stackoverflow > Groovy write to file with customized newline
Hardly any script (let alone whole applications) can do without file access and other input/output-related issues. The JDK addresses this need with its java.io and java.netpackages. It provides elaborate support with the File and URL classes and numerous versions of streams, readers, and writers.
However, the programmer is left with the repetitive, tedious, and error-prone task of managing I/O resources, such as properly closing an opened file even if exceptions occur while processing. This is where the GDK steps in and provides numerous methods that let you focus on the task at hand rather than thinking about I/O boilerplate code. This results in faster development, better readability of your code, and more stable solutions, because resource leaks are less likely with centralized error-handling. Having read chapter 5, you may correctly surmise that this is a job for closures.
In table 9.3 (If the target is File, Iterator over lines), you saw that File objects work with Object’s iteration methods. Listing 9.4 uses this approach to print itself to the console: The output is exactly what you see as listing 9.4. Assertions are used to show the use of any , findAll, and grep. Note that file.grep{it} returns only non-empty lines, because empty strings evaluate to false.
- Listing 9.4 File’s object iteration method examples
- file = new File('Listing_9_4_File_Iteration.groovy')
- file.each{println it}
- assert file.any {it =~ /File/}
- assert 3 == file.findAll{it =~ /File/}.size()
- assert 5 == file.grep{it}.size()
Traversing the filesystem:
Groovy follows the Java approach of using the File class for both files and directories, where a File object represents a location (not content, contrary to a common misconception). Using a File object from Groovy often includes calling its JDK methods in a property-style manner. For example, to display information about the current directory, you can use:
- file = new File('.')
- println file.name
- println file.absolutePath
- println file.canonicalPath
- println file.directory
- Listing 9.5 File methods for traversing the filesystem
- homedir = new File('/java/groovy')
- dirs = []
- homedir.eachDir{dirs << it.name } // Closure recording directory names
- assert ['bin','conf','docs','embeddable','lib'] == dirs
- cvsdir = new File('/cygwin/home/dierk/groovy')
- files = []
- cvsdir.eachFile{files << it.name} // Closure recording filenames
- assert files.contains('.cvsignore')
- assert files.contains('CVS')
- files = []
- cvsdir.eachFileMatch(~/groovy.*/){files << it.name} // Closure recording filenames matching a pattern
- assert ['groovy-core', 'groovy-native'] == files
- docsdir = new File('/java/groovy/docs')
- count = 0
- docsdir.eachFileRecurse{if (it.directory) count++} // Closure counting directories recursively
- assert 104 == count
Suppose we have a file example.txt in the data directory below our current one. It contains:
- line one
- line two
- line three
- println new File('data/example.txt').text
BY THE WAY
Listing 9.6 goes through some examples of file reading with more fine-grained control. The readLines method returns a list of strings, each representing one line in the input source with newline characters chopped.
- Listing 9.6 File-reading examples
- example = new File('data/example.txt')
- lines = ['line one','line two','line three']
- assert lines == example.readLines()
- example.eachLine {
- assert it.startsWith('line')
- }
- hex = []
- example.eachByte { hex << it }
- assert hex.size() == example.length()
- example.splitEachLine(/\s/){
- assert 'line' == it[0]
- }
- example.withReader { reader ->
- assert 'line one' == reader.readLine()
- }
- example.withInputStream { is ->
- assert 'line one' == is.readLines()[0]
- }
When the input source is made of formatted lines, splitEachLine can be handy. For every line, it yields a list of items to its closure determined by splitting the line with the given regular expression. Generally, the with<Resource> methods pass the <Resource> into the closure, handling resource management appropriately. So do the methodswithReader and withInputStream. The readLine method can then be used on such a given Reader or InputStream.
Writing to output destinations:
Listing 9.7 uses the corresponding methods for writing to an output destination. Writing a whole file at once can be achieved with File ’s write method; appending is done with append . The with<Resource> methods work exactly as you would expect. The use of withWriter and withWriterAppend is shown in the listing; withPrintWriter andwithOutputStream are analogous. The leftshift operator on File has the meaning of append.
- Listing 9.7 File-writing examples
- def outFile = new File('data/out.txt')
- def lines = ['line one','line two','line three']
- // Writing/appending with simple method calls
- outFile.write(lines[0..1].join("\n"))
- outFile.append("\n"+lines[2])
- assert lines == outFile.readLines()
- // Writing/appending with closures
- outFile.withWriter { writer ->
- writer.writeLine(lines[0])
- }
- outFile.withWriterAppend('ISO8859-1') { writer ->
- writer << lines[1] << "\n"
- }
- outFile << lines[2] // Appending with the leftshift operator
- assert lines == outFile.readLines()
The leftshift operator on Writer objects is a clever beast. It relays to Writer’s write method, which in the GDK makes a best effort to write the argument. The idea is to write a string representation with special support for arrays, maps, and collections. For general objects, toString is used.
If the argument is of type InputStream or Reader, its content is pumped into the writer. Listing 9.8 shows this in action.
- Listing 9.8 Using Writer’s smart leftshift operator
- reader = new StringReader('abc')
- writer = new StringWriter()
- writer << "\nsome String" << "\n"
- writer << [a:1, b:2] << "\n"
- writer << [3,4] << "\n"
- writer << new Date(0) << "\n"
- writer << reader << "\n"
- assert writer.toString() == '''
- some String
- [a:1, b:2]
- [3, 4]
- Thu Jan 01 08:00:00 CST 1970
- abc
- '''
- writer << reader
Finally, the leftshift operator on Writer objects has special support for arguments of type Writable. In general, a Writable is an object with a writeTo method: It knows how to write something. This makes a Writable applicable to:
- writer << writable
Filters and conversions:
There are times when ready-made resource handling as implemented by the with<Resource> methods is not what you want. This is when you can use the methodsnewReader , newInputStream , newOutputStream , newWriter , and newPrintWriter to convert from a File object to the type of resource you need.
Two other conversions of this kind are from String and StringBuffer to their respective Writer s via:
- StringWriter writer = myString.createStringWriter()
- StringBufferWriter sbw = myStringBuffer.createStringBufferWriter()
character or line by line. Listing 9.9 shows how you can use transformChar and transformLine for this task. They both take a closure argument that determines the transformation result. Whatever that closure returns gets written to the writer argument.
- Listing 9.9 Transforming and filtering examples
- reader = new StringReader('abc')
- writer = new StringWriter()
- // Transform ‘abc’ to ‘bcd’
- reader.transformChar(writer) { it.next() }
- assert 'bcd' == writer.toString()
- // Chop ‘line’ from each line of the example file
- reader = new File('data/example.txt').newReader()
- writer = new StringWriter()
- reader.transformLine(writer) { it - 'line' }
- assert " one\r\n two\r\n three\r\n" == writer.toString()
- // Read only lines containing “one”
- input = new File('data/example.txt')
- writer = new StringWriter()
- input.filterLine(writer) { it =~ /one/ }
- assert "line one\r\n" == writer.toString()
- // 1) Read only long lines
- writer = new StringWriter()
- writer << input.filterLine { it.size() > 8 }
- assert "line three\r\n" == writer.toString()
NOTE.
Finally, a frequently used conversion is from binary data to strings with base-64 encoding, where binary data is represented only in printable characters, as specified inRFC 2045. This can be useful for sending binary coded data in an email, for example. The name of this codec comes from it having 64 symbols in its “alphabet”, 7 just as the decimal system is base 10 (10 symbols: 0–9) and binary is base 2 (2 symbols: 0 and 1):
- byte[] data = new byte[256]
- for (i in 0..255) { data[i] = i }
- store = data.encodeBase64().toString()
- assert store.startsWith('AAECAwQFBg')
- assert store.endsWith ('r7/P3+/w==')
- restored = store.decodeBase64()
- assert data.toList() == restored.toList()
Base-64 encoding works with arbitrary binary data with no meaning attached to it. In order to encode objects instead, we need to venture into the world of serialization, which is the topic of the next section.
Streaming serialized objects:
Java comes with a serialization protocol that allows objects of type Serializable to be stored in a format so that they can be restored in VM instances that are disconnected in either space or time. Serialized objects can be written to ObjectOutputStreams and read from ObjectInputStreams. These streams allow making deep copies of objects, sending objects across networks, and storing objects in files or databases.
Listing 9.10 shows the special GDK support for reading serialized objects from a file. First, an Integer , a String , and a Date are written to a file. They are then restored with File’s new eachObject method. A final assertion checks whether the restored objects are equal to the original.
- Listing 9.10 Reading serialized objects from files
- file = new File('data/objects.dta')
- out = file.newOutputStream()
- oos = new ObjectOutputStream(out)
- objects = [1, "Hello Groovy!", new Date()]
- // Serialize each object in the list in turn
- objects.each {
- oos.writeObject(it)
- }
- oos.close()
- // Deserialize each object in turn
- retrieved = []
- file.eachObject { retrieved << it }
- assert retrieved == objects
- file.eachObject
- file.newObjectInputStream().eachObject
* Documentation > User Guide > Input Output
* Stackoverflow > Groovy write to file with customized newline
沒有留言:
張貼留言