我的文件的写入过程如下(在我称之为非集群的模式下)
- 将对象写入文件的当前位置。注意在另一个文件(称为索引文件)中写入的位置,以便我知道我将对象放在哪里。
- 通过写入零字节留出一些空间(随机 1/2/3/4 KB 的空间)
- 重复步骤 1 和 2
现在我决定从文件中读取对象。但我想用BufferedInputStream
. 但是,当我将 a 封装BufferedInputStream
在 ObjectInputStream 中时,在读取一些对象后会出现错误。我猜这发生在一次缓冲读取之后(即,缓冲区中可以容纳的尽可能多的对象被读取一次,下次我收到错误时)。
另一方面,将 aFileInputStream
直接封装在ObjectInputStream
作品中没有任何问题。
如果需要,我也会提供文件编写代码。随意询问有关以下代码的任何内容。
public class RecordsFileReader {
RecordsFile rFile;
Iterator itr;
FileInputStream fis;
ObjectInputStream ois;
// The constructor
public RecordsFileReader(RecordsFile rFile) throws IOException, ClassNotFoundException {
this.rFile = rFile;
fis = new FileInputStream(rFile.getFileName());
ObjectInputStream ois2 = new ObjectInputStream(new FileInputStream(rFile.getFileName() + ".index"));
rFile.recordsLocationList = (ArrayList <Long>) ois2.readObject();
itr = rFile.recordsLocationList.iterator();
/**********************************************************/
/* HERE IS THE PROBLEM. */
/* Doesnt work when I additionally use BufferedInputStream*/
/**********************************************************/
ois = new ObjectInputStream(fis);
/**********************************************************/
}
public Tuple readNext() throws IOException, ClassNotFoundException {
if(!itr.hasNext())
return null;
Long nextRecordPosition = itr.next();
fis.getChannel().position(nextRecordPosition);
//System.out.println((Tuple) ois.readObject());
return ((Tuple) ois.readObject());
}
public void close() throws IOException {
ois.close();
fis.close();
}
public boolean hasNext() {
return itr.hasNext();
}
}
public class RecordsFile {
boolean clustered;
private String fileName;
public RecordsFile(String fileName, boolean clustered) throws IOException {
this.fileName = fileName;
this.clustered = clustered;
}
/*
The byte positions at which the records are located in the file.
*/
ArrayList<Long> recordsLocationList= new ArrayList<Long>();
public String getFileName() {
return fileName;
}
}
这是导致错误的更改:
ois = new ObjectInputStream(new BufferedInputStream(fis, 4096));
而不是ois = new ObjectInputStream(fis);
错误是java.io.StreamCorruptionException: invalid type code : 00
编辑 :
我现在已经弄清楚了问题所在。当我的 fis 被定位到一个新位置时,我的 bis 没有被跳到那个新位置。相反,bis 试图仅从旧位置读取,因此例外