Friday, November 1, 2013

How to get top n and bottom n lines from a text file in a single pass ?

Some days ago, I came across a problem. The problem was to get the row-count , top n and bottom n number of lines from a text file in a single pass.
I thought for a while and remembered about a data-structure Queue that I had learned about in Data Structures and Algorithm course. I then wrote a simple Java code to get implementing Queue.
Below is the code I wrote, please read and give me feedbacks.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;

public class Test {
 private static Queue top=new LinkedList();
 private static Queue bottom=new LinkedList();
 private static int count=0;
 
 public static void main(String[] args) throws IOException{
  func(3);
  }
 
 //function to get count, top n, bottom n lines
 private static void func(int n) throws IOException{
  FileInputStream fstream = new FileInputStream("abc.txt");
  BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

  String strLine;

  //Read File Line By Line
  while ((strLine = br.readLine()) != null){
    count++;
    if(count<=n){
     top.add(strLine);    //initialize both top and bottom as top n 
     bottom.add(strLine);
    }else{
     bottom.remove();
     bottom.add(strLine);
        }
  }
  System.out.println(count);
  System.out.println(top.toString());
  System.out.println(bottom.toString());
  br.close();    
 }
}

No comments:

Post a Comment