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
dmoreAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

InteractiveMindCommented:
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
hoomanvCommented:
// 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
InteractiveMindCommented:
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
Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

hoomanvCommented:
> 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
InteractiveMindCommented:
You're right.

:)
0
dmoreAuthor Commented:
Thanks.But when I try to run this , I can see all lines being printed but the lastline is always 'null' .any ideas?
0
hoomanvCommented:
because the last call to readline returnes null, when you reach to EOF
0
hoomanvCommented:
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
mrigankCommented:
BufferedReader in = new BufferedReader(new FileReader( f )) ;
String str;lastLine;
while ((str = in.readLine()) != null) {
    lastLine = str;
}
in.close();
return lastLine;
0
dmoreAuthor Commented:
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
hoomanvCommented:
post your code where you save last lines
0
CEHJCommented:
>>You need to save them in a collection like a List
0
CEHJCommented:
Use hoomanv's code in a loop, adding to the List as you go along
0
dmoreAuthor Commented:
//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
mightyoneCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
mightyoneCommented:
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
CEHJCommented:
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
dmoreAuthor Commented:
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.