I read text data from big file line by line.
But I need to read just n-x lines(don’t read last x lines) .
How can I do it without reading whole file more than 1 time?
(I read line and immediately process it, so i can’t go back)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In this post I’ll provide you with two completely different approaches to solving your problem, and depending on your use case one of the solutions will fit better than the other.
Alternative #1
This method is memory efficient though quite complex, if you are going to skip a lot of contents this method is recommended since you only will store one line at a time in memory during processing.
The implementation of it in this post might not be super optimized, but the theory behind it stands clear.
You will start by reading the file backwards, searching for N number of line breaks. When you’ve successfully located where in the file you’d like to stop your processing later on you will jump back to the beginning of the file.
Alternative #2
This method is easy to comprehend and is very straight forward. During execution you will have N number of lines stored in memory, where N is the number of lines you’d like to skip in the end.
The lines will be stored in a FIFO container (First In, First Out). You’ll append the last read line to your FIFO and then remove and process the first entry. This way you will always process lines at least N entries away from the end of your file.
Alternative #1
This might sound odd but it’s definitely doable and the way I’d recommend you to do it; start by reading the file backwards.
SKIP_Nline breaksExample code:
The code below will strip off the last
42lines from/tmp/sample_fileand print the rest using the method described earlier in this post.Alternative #2
LinkedList<String>LinkedList<String>contains more lines than you’d like to skip, remove the first entry and process itExample code