Read a Specific Line of a File with Groovy

It's sloppy and wasteful, but you can do

log.info "Line 5: " +  myFile.readLines().get(4)

If you don't want it all in memory, you can do:

String readLine( File f, int n ) {
  String line = null
  f.withReader { r ->
    while( n-- > 0 && ( ( line = r.readLine() ) != null ) ) ;
  }
  line
}

Then, to print the 5th line:

File infile = new File("C:\\Documents and Settings\\ABCEDFG\\Desktop\\soapUI\\params.txt")
String line = readLine( infile, 5 )
println line

However, if you want to read many lines in a random order access way, this might be wasteful as you will spool down the file from the start every time. However, if you can't load it into memory as it's too big, there's not much else you can do

Tags:

Groovy