Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

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.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6929179
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T11:17:02+00:00 2026-05-27T11:17:02+00:00

I read text data from big file line by line. But I need to

  • 0

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)

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T11:17:03+00:00Added an answer on May 27, 2026 at 11:17 am

    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.

    1. Seek to the end of the file
    2. Read (and discard) bytes (towards the beginning of the file) until you’ve found SKIP_N line breaks
    3. Save this position
    4. Seek to the beginning of the file
    5. Read (and process) lines until you’ve come down to the position you’ve stored away

    Example code:

    The code below will strip off the last 42 lines from /tmp/sample_file and print the rest using the method described earlier in this post.

    import java.io.RandomAccessFile;
    import java.io.File;
    
    import java.lang.Math;
    
    public class Example {
      protected static final int SKIP_N = 42;
    
      public static void main (String[] args)
        throws Exception
      {
        File fileHandle            = new File ("/tmp/sample_file");
        RandomAccessFile rafHandle = new RandomAccessFile (fileHandle, "r");
        String s1                  = new String ();
    
        long currentOffset = 0;
        long endOffset     = findEndOffset (SKIP_N, rafHandle);
    
        rafHandle.seek (0);
    
        while ((s1 = rafHandle.readLine ()) != null) {
          ;   currentOffset += s1.length () + 1; // (s1 + "\n").length
          if (currentOffset >= endOffset)
            break;
    
          System.out.println (s1);
        }
      }
    
      protected static long findEndOffset (int skipNLines, RandomAccessFile rafHandle)
        throws Exception
      {
        long currentOffset = rafHandle.length ();
        long endOffset     =  0;
        int  foundLines    =  0;
    
        byte [] buffer      = new byte[
          1024 > rafHandle.length () ? (int) rafHandle.length () : 1024
        ];
    
        while (foundLines < skipNLines && currentOffset != 0) {
          currentOffset = Math.max (currentOffset - buffer.length, 0);
    
          rafHandle.seek      (currentOffset);
          rafHandle.readFully (buffer);
    
          for (int i = buffer.length - 1; i > -1; --i) {
            if (buffer[i] == '\n') {
              ++foundLines;
    
              if (foundLines == skipNLines)
                endOffset = currentOffset + i - 1; // we want the end to be BEFORE the newline
            }
          }
        } 
    
        return endOffset;
      }
    }
    


    Alternative #2

    1. Read from your file line by line
    2. On every successfully read line, insert the line at the back of your LinkedList<String>
    3. If your LinkedList<String> contains more lines than you’d like to skip, remove the first entry and process it
    4. Repeat until there are no more lines to be read

    Example code

    import java.io.InputStreamReader;
    import java.io.FileInputStream;
    import java.io.DataInputStream;
    import java.io.BufferedReader;
    
    import java.util.LinkedList;
    
    public class Example {
      protected static final int SKIP_N = 42; 
    
      public static void main (String[] args)
        throws Exception
      {
        String line;
    
        LinkedList<String> lli = new LinkedList<String> (); 
    
        FileInputStream   fis = new FileInputStream   ("/tmp/sample_file");
        DataInputStream   dis = new DataInputStream   (fis);
        InputStreamReader isr = new InputStreamReader (dis);
        BufferedReader    bre = new BufferedReader    (isr);
    
        while ((line = bre.readLine ()) != null) {
          lli.addLast (line);
    
          if (lli.size () > SKIP_N) {
            System.out.println (lli.removeFirst ());
          }   
        }   
    
        dis.close (); 
      }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need to read text data from file, where there are different types of
I need to read line by line from text file (log files from server)
I'm using scanner to read a text file line by line but then how
In php how can I read a text file and get each line into
I am trying to read in data from a text file using numpy.loadtxt with
Hi there I have to read data from text file into the array in
I want to read both formatted text and binary data from the same iostream.
I am trying to read in a text file from an SQL query (SQL
I have an application that imports data read from text files from a directory
How do I read text from the (windows) clipboard with python?

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.