Posted By

kolmogorov on 03/16/09


gzip eachLine GZIPInputStream BufferedReader

Versions (?)

Reading first line, then rest of file line by line with eachLine (+ gzip support)

 / Published in: Groovy

Read the first (or some number) of lines of file to treat special (e.g. the first line is column headings), then use eachLine to read in rest of file. Also illustrate simple use of GZIPInputStream. Other experiments had me convinced that eachLine always reset to beginning of stream, but apparently not.

  1. #!/usr/bin/env groovy
  3. import*;
  5. fileName = args[0]
  7. // Create a GZIPInputStream...
  8. // And a reader so we get the nice readLine...
  10. // Read the special first line...column headings say.
  11. firstLine = reader.readLine()
  12. println "firstLine: $firstLine"
  14. // Read the rest of the file...reader picks up where
  15. // it was left off with eachLine
  16. reader.eachLine{line->
  17. println "line: $line"
  18. }

Report this snippet  


RSS Icon Subscribe to comments
Posted By: kolmogorov on March 16, 2009

If you aren't dealing with gzipped files, you could also use the withReader syntax, which is a bit less verbose. Something like:

new File("").withReader{r->
    line = r.readLine();
    println "first line: $line"
            println "fields on line: $fields"

You need to login to post a comment.