?
Solved

read last line of a file -urgent

Posted on 2006-04-07
18
Medium Priority
?
4,565 Views
Last Modified: 2012-05-05
Hi
There is a requirement that I should read just the last record from a file.I know I can randomfileaccess but can anyone please give me a sample program so that I can work based on it.


Thanks in advance
0
Comment
Question by:dmore
  • 5
  • 4
  • 3
  • +3
18 Comments
 
LVL 25

Expert Comment

by:InteractiveMind
ID: 16400731
Well, I don't see how you can randomaccess the file, because you don't know the offset of the start of the end line.

So, I imagine you'd just read in each line from the file, overwriting the previous one, until you've gone through each line in the file - and will be left with the last one.

For example:

public static String getLastLine( File f ) throws Exception
{
    BufferedReader in = new BufferedReader(new FileReader( f )) ;
    String str;
    while ((str = in.readLine()) != null) {}
    in.close();
    return str ;
}
0
 
LVL 14

Expert Comment

by:hoomanv
ID: 16401209
// open file
RandomAccessFile(File file, String mode) // open for read so mode = "r"

// get file length
len = length() // returns a long

// seek to the end of file, but 1 less
seek(len - 1)

while {
    read() // read one byte. each read increases the current file pointer by one
    if the byte is '\n' or you reach the start of file
        break
    seek(getFilePointer() - 2) // go back 2 steps
}

you are now after the last '\n'
so read till you reach the end of file
0
 
LVL 25

Expert Comment

by:InteractiveMind
ID: 16401280
In some cases, it may be more efficient to use my technique.

But if that technique is more suitable in your case, then you should probably check for both "\n" and "\r\n" - otherwise you may miss the delim ;)
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 14

Expert Comment

by:hoomanv
ID: 16401439
> In some cases, it may be more efficient to use my technique.
yes it is when the file size is not large
the unix tail command also uses mine ;-)

> you should probably check for both "\n" and "\r\n"

in this case, every time you reach a '\n' you have to iterate one more time to make sure there is also a '\r' behind that.
0
 
LVL 25

Expert Comment

by:InteractiveMind
ID: 16401476
You're right.

:)
0
 

Author Comment

by:dmore
ID: 16401532
Thanks.But when I try to run this , I can see all lines being printed but the lastline is always 'null' .any ideas?
0
 
LVL 14

Expert Comment

by:hoomanv
ID: 16401544
because the last call to readline returnes null, when you reach to EOF
0
 
LVL 14

Assisted Solution

by:hoomanv
hoomanv earned 90 total points
ID: 16401605
while ((str = in.readLine()) != null) {}
last call to readline will set str = null
you need to make sure if in.readLine() is not null then assign it to str
while ((line = in.readLine()) != null) {
    str = line;
}
0
 
LVL 5

Expert Comment

by:mrigank
ID: 16401643
BufferedReader in = new BufferedReader(new FileReader( f )) ;
String str;lastLine;
while ((str = in.readLine()) != null) {
    lastLine = str;
}
in.close();
return lastLine;
0
 

Author Comment

by:dmore
ID: 16401699
Thanks it works , but I have a new problem.I have a directory in which I am getting all the files and then I have go to each of these files and get the 'last line' from them.in this case it loops through files but only the line of last file is saved.Any suggestions ?
0
 
LVL 14

Expert Comment

by:hoomanv
ID: 16401722
post your code where you save last lines
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 16401818
>>You need to save them in a collection like a List
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 16401838
Use hoomanv's code in a loop, adding to the List as you go along
0
 

Author Comment

by:dmore
ID: 16401961
//This is what Iam trying to do ...Ima string all the filenames in the directory in 'filelist' array as you can see below,The pointer variable is used for looping through the files.I open each file read it's last line and go to next one.I need a way to collate these...Thanks

public String getLastLine(){
            try {
                  if( pointer > (filelist.length-1)) return null;
                  for (pointer=0;pointer<filelist.length;pointer++) {
                        String filename = filelist[pointer];
                        File f = new File(filename);
                        System.out.println(f);
                        if( f.exists() ){
          BufferedReader in = new BufferedReader(new FileReader( f )) ;
          while ((ltr = in.readLine()) != null) {str=ltr;}
          in.close();
                        }
                  }
            } catch (IOException e) {
                  e.printStackTrace();
            }
          return str ;
      }
0
 
LVL 6

Accepted Solution

by:
mightyone earned 60 total points
ID: 16402167
public HashMap getLastLine(){
               HashMap map = new HashMap();
          try {

               if( pointer > (filelist.length-1)) return null;
               for (pointer=0;pointer<filelist.length;pointer++) {
                    String filename = filelist[pointer];
                    File f = new File(filename);
                    System.out.println(f);
                    if( f.exists() ){
         BufferedReader in = new BufferedReader(new FileReader( f )) ;
         while ((ltr = in.readLine()) != null) {str=ltr;}
         in.close();
                    map.put(filelist[i],str);
                    }
               }
          } catch (IOException e) {
               e.printStackTrace();
          }
         return map ;
     }
0
 
LVL 6

Expert Comment

by:mightyone
ID: 16402188
if you just need the content of last line and don't care about the filename you read it from.

 public String getLastLine(){
               StringBuilder sb = new StringBuilder();
          try {

               if( pointer > (filelist.length-1)) return null;
               for (pointer=0;pointer<filelist.length;pointer++) {
                    String filename = filelist[pointer];
                    File f = new File(filename);
                    System.out.println(f);
                    if( f.exists() ){
         BufferedReader in = new BufferedReader(new FileReader( f )) ;
         while ((ltr = in.readLine()) != null) {str=ltr;}
         in.close();
                    sb.append(str);
                    }
               }
          } catch (IOException e) {
               e.printStackTrace();
          }
         return sb.toString() ;
     }
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 16402576
In general, you'll find working with File[] from File.listFiles to be more powerful and flexible. Don't use BufferedReader - this is a very inefficient way to do things - use hoomanv's approach, which incidentally can be made more efficient still by not doing this:

>>
you are now after the last '\n'
so read till you reach the end of file
>>

but doing this

stringBuilder.insert(0, byteRead)

as you go along.

Of course this assumes 'ascii' encoding, and if that assumption can't be made, then a Reader will be necessary unless you want to do your own character decoding
0
 

Author Comment

by:dmore
ID: 16424874
Even though , I have split points between mightyone  & hoomanv who were close to what I required .Thanks to everyone who have contributed to this query.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses
Course of the Month14 days, 15 hours left to enroll

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question