Emil D
Emil D

Reputation: 1904

Start reading a text file from a particular line

Is a way to pen a text file, read a few lines, close it, re-open it and start reading from the line where you left off before? Or do you always have to start from the top?

Upvotes: 1

Views: 1743

Answers (4)

JohnKubik
JohnKubik

Reputation: 79

You sure can! This is not going to be the fastest method, but it is going to work. And, by the way, the people who responded to your question by telling you that you should just start reprocessing from the beginning of the file TOTALLY missed the point of your question. There are an ample amount of reasons to want to return to where you left off.

Here is some code I wrote that allows you to store a counter value, and then iterate through the file until you re-reach the counter value... at which point the loop takes affect and process what is in the loop for the remaining lines.

Cheers!

//define input text file
def file = new File('C:\\inputtextfile.txt')
//define file for the last referenced counter
def CountFile = new File ('C:\\prime\\lastcount.txt')

//if the counter was null set it to zero
if (CountFile.eachLine({it}) == null){
CountFile.write('0')
}

//read the counter into a value
StartLine = CountFile.eachLine( {it} ) as long
//set the first line of the file
lineCount=0

file.eachLine { line  ->
if (lineCount >= StartLine){


//write the counter to a text file
////////////////////////////////////////////////////////////////
CountFile.write(lineCount.toString())
    lineCount++
///////////////////////////////////////////////////////////////
}

Upvotes: 1

mmoment
mmoment

Reputation: 1289

Can't you just save the line number externally and jump to / seek the desired position?

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533442

I would just start from the top each time. This is the simplest and possibly not much slower. You can use a RandomAccessFile but you would have to wrap it with your own line reader (as well as place some check that the file hasn't changed in an incompatible manner)

Upvotes: 0

David Weiser
David Weiser

Reputation: 5195

I'm pretty sure every time you open a file, it starts you from the beginning.

Upvotes: 0

Related Questions