我的文件写入过程如下(在我称之为非聚集的模式下):
另一方面,直接将
如果需要,我也可以提供文件写入代码。如果对下面的代码有任何问题,请随意询问。
现在我决定从文件中读取对象。但是我想使用
- 将一个对象写入文件的当前位置。在另一个文件(称为索引文件)中记录写入的位置,以便知道我放置了哪些对象。
- 通过写入零字节留出一些空间(随机1/2/3/4 KB的空间)
- 重复步骤1和2
BufferedInputStream
。然而,当我将BufferedInputStream
封装在ObjectInputStream
中时,读取一些对象后会出现错误。我猜测这是发生在一次缓冲读取之后(即一次读取尽可能多的对象,下一次就会出现错误)。另一方面,直接将
FileInputStream
封装在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仅尝试从旧位置读取,因此出现异常。
ois = new ObjectInputStream(new BufferedInputStream(fis, 4096));
替代ois = new ObjectInputStream(fis);
- AnkurVj