Versions Compared


  • This line was added.
  • This line was removed.
  • Formatting was changed.


Code Block
def fw= new FileWriter('TestFile.txt')

//These methods are available for all writers, not just for FileWriter:
[ 'a', 'b' ].each{ fw.write(it as char) } //write out the supplied character
[ 'cd', 'efg' ].each{ fw.write(it) } //write out the supplied string
fw.write(['h', 'i', 'j'] as char[])
fw.write(['h', 'i', 'j', 'k', 'l', 'm'] as char[], 3, 2)
    //write 2 chars from array starting at index 3
fw.write('klmnopq', 2, 4) //write 4 chars from string starting at index 2
fw.append('q' as char). //these Java 5.0 methods allow chaining
   append('uvwxyz', 2, 6)
       //use subsequence from index 2 to index 6 of supplied string
try{ fw.write('z'); assert 0 }catch(e){ assert e instanceof IOException }
    //no writing after file closed

assert new File('TestFile.txt').readLines() == [ 'abcdefghijklmnopqrstuvwxyz' ]

def fr= new FileReader('TestFile.txt')

//These methods are available for all readers, not just for FileReader:
  assert == 'a'
  fr.skip(2) //skip over, here, 2 chars
  def ca2= new char[3]
  assert ca2.toList()*.toString() == ['d', 'e', 'f']
  def ca3= new char[6]

  assert, 3, 2) == 2 //fill ca3 with 2 elements from index 3,
                                 //return num of elements copied, here, 2
  assert ca3.toList()*.toString() == ['\0', '\0', '\0', 'g', 'h', '\0']
                                 //similar to InputStream method
  assert == -1 //return -1 if already at end-of-stream

  //true if this input stream support the mark() and reset() methods...
  if( fr.markSupported() ){
        //reset reading to beginning of stream if mark() hasn't ever been called
    assert == 'a' as char
    fr.mark(0) //mark this position in the stream; argument has no meaning here char[4])
    fr.reset() //reset reading to where the last mark() method was called
    assert == 'b' as char
  try{; assert 0 }catch(e){ assert e instanceof IOException }

new File('TestFile.txt').delete() //delete the file used by this example

Closing Streams

When we write to an output stream or writer such as FileWriter, we should always close() it in some way:


Although the examples above are for files, they're all available for streams, readers, and writers around all other resources also.

Resource-specific Streams

When we met the FileInputStream, FileOutputStream, FileReader, and FileWriter in the above examples, we constructed them with a single String. We can also construct them with a file, and add an 'append' flag: