Question

I want to re-read a file by adding data to the file when it reaches EOF. But second read after adding data isn't working.

This is my code

       File f = new File("sample.csv");
       byte[] bb= new byte[(int)f.length()];
      RandomAccessFile raf = new RandomAccessFile (f, "r");
      int bytesread=0;
      bytesread = raf.read(bb, 0,(int)f.length());
              //bytesread =302 or something

      raf.seek(f.length());
      Thread.sleep(4000);
      bytesread = raf.read(bb,0,2); 
    //bytesread = -1 instead of 2  
      raf.close();

What I'm doing is initially i'm reading the contents of the file, during the first read say my bytesread = 302 or something. Now Seeking the pointer to EOF and adding some data to my file and reading it again but instead of desired result bytesread =2, I'm getting bytesread as -1. Can anyone tell me what is the prob with my program?

Était-ce utile?

La solution

For most streams, once you read the end of the file, you can't read again (RandomAccessFIle might be different but I suspect not)

What I would do is only read up to, but not including the end of the file, which works of other streams.

e.g.

int positionToRead = ...
int length = f.length();
// only read the bytes which are there.
int bytesRead = f.read(bb, 0, length - positionToRead); 

This should work repeatedly.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top