Follow us on
You are here: Home > All Posts > N/A > Wipro > technical

Java : Quick way to read to get the last line from a File
Posted by Ankit ( Verified Professional) from Wipro                                              
Posted On 1 year ago | Last Modified 1 year ago | Visit582
City: N/A

There are different ways to achieve this -

First One -

try { 

                 File f = new File("data.txt");

                FileInputStream fis = new FileInputStream(f);

                 byte[] content = new byte[fis.available()];

                 fis.read(content);

                 String data = new String(content);

                

              String[] split = data.split(System.getProperty("line.separator"));

                 String lastLine = "";

                 if(split.length > 0){

                       lastLine = split[split.length -1];

                 }

                 System.out.println(lastLine);

           } catch (Exception e) {

                 // TODO Auto-generated catch block

                 e.printStackTrace();

           }

Second One -

You may try the RandomAccessFile in java.io
 
First goto the last position
 
RandomAccessFile rfile = new RandomAccessFile(file,"r")
      
rfile.seek(file.length())

Third One -

FileInputStream fis=new FileInputStream("D:\\ test\\sample.txt");

                  

String fileContent = new Scanner(fis).useDelimiter("\\Z").next();

Comments




Related Posts View All
Tags :