Read a specific line of a file with Groovy

Can someone help me read the file line by line,

I have this code, but this code will print all the content. I need to display only the fifth (or specific) line by line, so I want to dynamically access and print any line. I need to print the 5th line of a text file.

//read from file

myFile = new File("C:\\Documents and Settings\\ABCEDFG\\Desktop\\soapUI\\params.txt")
printFileLine = { log.info "File line: " + it }
myFile.eachLine(0, printFileLine)

Please help - Support your help in advance!

^ Thank you

+5
source share
4 answers

It's messy and wasteful, but you can do

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

If you do not want all this 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

, , , . , , ,

+4

. 2 :

  • .
  • , N, 0 (N-1).

:

- . , , N. N, , N- .

+1

.

File file = new File('input.txt')
def lines = file.readLines()
println(lines[3])

4-

0

All Articles