Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Java-get-example Java Get Last Line of File

Related Tutorials


 
 

Share on Google+Share on Google+

Java Get Last Line of File

Advertisement
In This Tutorial we want to describe you a code that helps you in understanding Get Last Line of File in Java.

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
Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 5, 2008

Related Tutorials

Discuss: Java Get Last Line of File   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com