Created
October 14, 2013 01:42
-
-
Save ravichandrae/6969509 to your computer and use it in GitHub Desktop.
This program prints the last k lines from a given file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.FileNotFoundException; | |
import java.io.FileReader; | |
import java.util.Scanner; | |
/** | |
* Created with IntelliJ IDEA. | |
* User: Ravi | |
* Date: 10/14/13 | |
* Time: 6:36 AM | |
* To change this template use File | Settings | File Templates. | |
*/ | |
public class PrintLastKLines { | |
public static void main(String[] args) | |
{ | |
try { | |
Scanner reader = new Scanner(System.in); | |
String strFilePath = reader.nextLine(); | |
Scanner fileReader = new Scanner(new FileReader(strFilePath)); | |
int kLines = Integer.parseInt(reader.nextLine()); | |
String[] strArrayLines = new String[kLines]; | |
int nLines = 0; //Total number of lines in the file | |
int ind = 0; //running index | |
if( kLines > 0) | |
{ | |
while( fileReader.hasNext() ) | |
{ | |
strArrayLines[ind] = fileReader.nextLine(); | |
ind = (ind + 1)%kLines; | |
nLines++; | |
} | |
} | |
int i; | |
//If the file contains less number of lines than kLines | |
if( nLines < kLines ) | |
{ | |
//print from the beginning of the array | |
for( i = 0; i < nLines; i++) | |
{ | |
System.out.println( strArrayLines[i] ); | |
} | |
} | |
else | |
{ | |
for( i = 0; i < kLines; i++ ) | |
{ | |
System.out.println( strArrayLines[ind] ); | |
ind = (ind+1) % kLines; | |
} | |
} | |
} | |
catch (FileNotFoundException fnfe) | |
{ | |
System.out.println( fnfe.getMessage() ); | |
} | |
catch(NumberFormatException nfe) | |
{ | |
System.out.println( nfe.getMessage() ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment