Versions Compared

Key

  • 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.flush()
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('rstuv').
   append('uvwxyz', 2, 6)
       //use subsequence from index 2 to index 6 of supplied string
fw.close()
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:
if(fr.ready()){
  assert fr.read() == 'a'
  fr.skip(2) //skip over, here, 2 chars
  def ca2= new char[3]
  fr.read(ca2)
  assert ca2.toList()*.toString() == ['d', 'e', 'f']
  def ca3= new char[6]

  assert fr.read(ca3, 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
  fr.skip(20)
  assert fr.read(ca3) == -1 //return -1 if already at end-of-stream

  //true if this input stream support the mark() and reset() methods...
  if( fr.markSupported() ){
    fr.reset()
        //reset reading to beginning of stream if mark() hasn't ever been called
    assert fr.read() == 'a' as char
    fr.mark(0) //mark this position in the stream; argument has no meaning here
    fr.read(new char[4])
    fr.reset() //reset reading to where the last mark() method was called
    assert fr.read() == 'b' as char
  }
  fr.close()
  try{ fr.read(); 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:

...