Link to home
Start Free TrialLog in
Avatar of dmore
dmore

asked on

read last line of a file -urgent

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
Avatar of InteractiveMind
InteractiveMind
Flag of United Kingdom of Great Britain and Northern Ireland image

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 ;
}
Avatar of hoomanv
// 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
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 ;)
> 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.
You're right.

:)
Avatar of dmore
dmore

ASKER

Thanks.But when I try to run this , I can see all lines being printed but the lastline is always 'null' .any ideas?
because the last call to readline returnes null, when you reach to EOF
SOLUTION
Avatar of hoomanv
hoomanv
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
BufferedReader in = new BufferedReader(new FileReader( f )) ;
String str;lastLine;
while ((str = in.readLine()) != null) {
    lastLine = str;
}
in.close();
return lastLine;
Avatar of dmore

ASKER

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 ?
post your code where you save last lines
>>You need to save them in a collection like a List
Use hoomanv's code in a loop, adding to the List as you go along
Avatar of dmore

ASKER

//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 ;
      }
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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() ;
     }
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
Avatar of dmore

ASKER

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.