Posted By

kolmogorov on 03/16/09


Tagged

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
  2.  
  3. import java.util.zip.*;
  4.  
  5. fileName = args[0]
  6.  
  7. // Create a GZIPInputStream...
  8. // And a reader so we get the nice readLine...
  9.  
  10. // Read the special first line...column headings say.
  11. firstLine = reader.readLine()
  12. println "firstLine: $firstLine"
  13.  
  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  

Comments

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("simple.tab").withReader{r->
    line = r.readLine();
    println "first line: $line"
    r.splitEachLine("\t"){fields->
            println "fields on line: $fields"
    }  
}

You need to login to post a comment.