简体   繁体   English

使用随机访问重新读取文件

[英]Re-reading a file using Random Access

I want to re-read a file by adding data to the file when it reaches EOF. 我想通过在文件到达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. 我正在做的是,最初我正在读取文件的内容,在第一次读取期间说我的字节数= 302或其他内容。 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. 现在,寻找指向EOF的指针并将一些数据添加到我的文件中,然后再次读取它,但是不是期望的结果byteread = 2,而是将byteread读取为-1。 Can anyone tell me what is the prob with my program? 谁能告诉我程序的概率是多少?

For most streams, once you read the end of the file, you can't read again (RandomAccessFIle might be different but I suspect not) 对于大多数流,一旦您读取了文件的末尾,就无法再次读取(RandomAccessFIle可能有所不同,但我怀疑没有)

What I would do is only read up to, but not including the end of the file, which works of other streams. 我要做的只是读取文件的末尾,但不包括文件末尾,其他流都可以使用。

eg 例如

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. 这应该重复工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM