[an error occurred while processing this directive]

Java Get Last Line of File

                         

In This Tutorial we want to describe you a code that helps you in understanding Get Last Line of File in Java . For this we have a class name "Get Last Line of File". Inside the main method we create an instance of file class by using a new operator and passing a text .txt as a argument.

1)Input Stream Reader  - This is used to read  the byte and decode  it into character stream from the text.txt present in a file.

2)Buffered Reader- This is used to read the character stream  from the text.txt present in  stream reader.

We declare a String object name line using new string operator.

3)file.getname( )-This  method return you the name of the file printed by System.out.println.

While loop evaluate the condition  weather the stream is ready to read

4)br.readline( )-This method is used to read the whole line of the Text.txt and store in line object of string class, that is further printed by System.out.println.

Finally the last line of file is printed by the System.out.println.

GetLastLineOfFile.java
import java.io.*;

public class GetLastLineOfFile {

    public static void main(String args[]) throws Exception {

        File file = new File("text.txt");

        InputStreamReader streamReader =
                new InputStreamReader(new FileInputStream(file));
        
        BufferedReader br = new BufferedReader(streamReader);

        String line = new String();
        System.out.println(file.getName());
        System.out.println("================");
        while (br.ready()) {
           line = br.readLine();
            System.out.println(line);
        }
        System.out.println("\n================");
        System.out.println("Last line of the file is : ");
        System.out.println(line);
    }
}

Output
text.txt
================
hi.
hi..
hi...
hi....
hi.....
hi......
hi.......
hi........
hi.........
hi..........

================
Last line of the file is : 
hi..........

Download code

                         

[an error occurred while processing this directive]