Friday, February 8, 2013

Printing Last n lines in a file.

Question: Print the last n lines of a file in one iteration

Solution: This problem is similar to finding nth element from the last in a linked list. We can have 2 variables one from pointing towards the start and the other for the end of the file. First move the first pointer N lines ahead in a file. Then start incrementing the second pointer one line ahead and at the same time increment first pointer one line ahead till we hit the EOF with the first pointer. Once we hit the EOF, 2nd pointer will be at the nth line from the end of the line. Start printing the lines till we reach the end of the file.


class PrintLastN {
public void PrintLastNLinesOfFile(String fileName, int numberOfLines) {
BufferedReader pointer1 = null;
BufferedReader pointer2 = null;
try {
if (numberOfLines <= 0)
throw new Exception(
"Invalid Number of Lines: Number of lines have to be greater than 0");
int i = 0;
pointer1 = new BufferedReader(new FileReader(fileName));
while (pointer1.readLine() != null) {
if (i == numberOfLines) {
pointer2 = new BufferedReader(new FileReader(fileName));
} else if (i > numberOfLines) {

if (pointer2 != null) {
String line = "";
while ((line = pointer2.readLine()) != null) {
} else {
.println("Invalid Number of Lines: Number of lines are less than expected");
} catch (Exception ex) {
} finally {

No comments: