注意:不是重复,因为这里我们不仅要写入对象,还要写入整个文件,然后再读回来。
我使用 ObjectOutputStream
创建了一个包含 3 个对象的 File
,
字符串
字符串
文件
(大小在 [1 到 1.5]GB 之间)
下面是我用来编写文件
byte[] BUFFER = new byte[1024*32];
FileInputStream fis = new FileInputStream("ThisIsTheFile.xyz");
FileOutputStream fos = new FileOutputStream("abcd.dat", true);
ObjectOutputStream oos = new ObjectOutputStream(fos);
String fileId = "BSN-1516-5287B-65893", fTitle = "Emberson Booklet";
for(int i = 0; i < 3; i++){
if(i == 0){
oos.write(fileId.getBytes(), 0, fileId.length());
}else if (i == 1){
oos.write(fTitle.getBytes(), 0, fTitle.length());
}else{
InputStream is = new BufferedInputStream(fis);
int bytesRead = -1;
while((bytesRead = is.read(BUFFER)) != -1){
oos.write(BUFFER, 0, bytesRead);
}
is.close();
}
}
fileId = fTitle = null;
oos.flush();
oos.close();
fos.flush();
fos.close();
fis.close();
现在我的问题是:
- 我不想中断
Java 堆空间
,因此使用 32KB 字节缓冲技术同时读取和写入大型File
流。 - 我是否将这三个
Object
分别正确地写在一个文件中? - 最后但同样重要的是,我应该如何通过
“abcd.dat”文件
通过ObjectInputStream
检索上面所说的所有 3 个Object
>?
请帮忙。
最佳答案
I have create a file with 3 single objects
没有。您创建了一个没有 对象和大量字节的文件,并且无法判断一个字节序列在哪里停止,另一个字节序列从哪里开始。使用 writeObject(),
并使用 readObject()
读取它们。按照您的方式,根本没有使用 ObjectOutputStream
的意义。
注意:附加到此文件将不起作用。参见 here为什么。
关于java - 如何在 Java 中使用 ObjectInputStream 读取不同的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34774147/