Thursday, March 7, 2013

Program to print last 10 lines of a file in Java

There are two ways to print the last 10 lines of a file.
            1.Go through the file and count the number of lines in that file . Lets say a file contains 100 lines. Read the file again and print the lines from 91 to 100 . Here you need to traverse the file two times .
            2.Create a string array to store the latest 10 lines when you are reading the file and print last 10 lines finally. Second method is given below .

Code : (in JAVA)
public static void printLastTenLines(String args[])
{
String []str = new String[10];
int count=0,i;
try
{
FileInputStream fstream = new FileInputStream("C:\\inputfile.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null)
{
str[count++]=strLine;
if(count==10)
count=0;
}
for(i=count;i<10;i++)
{
System.out.println(str[i]);
}
for(i=0;i<count;i++)
{
System.out.println(str[i]);
}
in.close();
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
view raw last10.java hosted with ❤ by GitHub
Please let me know if you have any questions .

No comments: