我想通过在文件到达EOF时向文件添加数据来重新读取文件。但是添加数据后的第二次读取不起作用。
这是我的代码
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();
我正在做的是最初我正在阅读文件的内容,在第一次阅读时说我的字节读取= 302或其他东西。现在寻找指向 EOF 的指针并将一些数据添加到我的文件中并再次读取它,但不是所需的结果字节读取 =2,而是我得到的字节读取为 -1。谁能告诉我我的程序有什么问题?
对于大多数流,一旦你读取了文件的末尾,你就无法再次读取(RandomAccessFIle可能不同,但我怀疑不是)
我要做的是只读取,但不包括文件的末尾,该文件适用于其他流。
例如
int positionToRead = ...
int length = f.length();
// only read the bytes which are there.
int bytesRead = f.read(bb, 0, length - positionToRead);
这应该反复工作。