Guillaume Laforgue sobre E/S

Véase Heads-up on File and Stream groovy methods por Guillaume Laforgue:

In the same spirit, I decided to add some append() methods to append text at the end of the File.

  f = new File("myFile.txt").append("Hello World\n")
  f.append("Hello again, that's me!")

You can also specify the encoding. Of course, don't write in the same file with different encodings, no editors would be able to read it ;-)

f = new File("myFile.txt").append("Hello World\n", "UTF-16BE")
f.append("Hello again, that's me!", "UTF-16BE")

Missing newWriter() methods have been added. It's now possible to specify the encoding used to write files, and optionally to specify wether we're in append mode.

wrter = new File("myText.txt").newWriter("UTF-8", true)
writer.write("\u20AC: euro symbol\n")
writer.write("$: dollar symbol\n")
writer.close()

Previously, when creating a new Reader from a file, the encoding was automatically guessed, thanks to CharsetToolkit I had implemented which smartly guessed the charset used to encode the file. Now, it is possible to overide this mechanism:

      reader = new File("myText.txt").newReader("UTF-8")

I extended the withWriter methods, so that we may specify an encoding, and also specify the append more:

// no need of course to close the writer, 
// since it's gracefully taken care of by the method
newFile("myText.txt").withWriterAppend("UTF-8") { writer |
    writer.write("\u20AC: euro symbol\n")
    writer.write("$: dollar symbol\n")
}

In the example above, you may also use the new writeLine() method on BufferedReader, which is cleaner than appened "\n" after each call to write(), so the example becomes:

newFile("myText.txt").withWriterAppend("UTF-8") { writer |
    writer.writeLine("\u20AC: euro symbol") // cleaner than "\n" obviously
    writer.writeLine("$: dollar symbol")
}

Note that it appends a platform dependant new line.

I've finally changed the readBytes() method to return an array of bytes instead of a List of Bytes which was quite ineficient:

bytes = new File("myText.txt").readBytes()

With all these methods, I thing we pretty can do anything we want! We should certainly cover all the scope of IO methods, especially of text files with optional specification of the encoding used.

Casiano Rodríguez León
2010-04-30