简体   繁体   English

如何使用Java中的ObjectInputStream读取不同的Object

[英]How to read different Object using ObjectInputStream in Java

Note: it's not a duplicate, because here we want to write not only Objects, but also a whole file, then read it back. 注意:它不是重复的,因为在这里我们不仅要写对象,还要写整个文件,然后再读回来。

I have created a single File with 3 Objects using ObjectOutputStream , 我使用ObjectOutputStream创建了一个包含3个对象的File

  1. String
  2. String
  3. File ( size is between [1 to 1.5]GB ) File (大小介于[1到1.5] GB之间)

Below is my code whichever I have used to write the File 以下是我用来编写File

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();

Now my problem is: 现在我的问题是:

  1. I don't want to interrupt the Java Heap Space so read & write the large File streams using 32KB bytes buffer technique simultaneously. 我不想中断Java Heap Space因此同时使用32KB字节缓冲技术读写大型File流。
  2. Am I writing these three Object inside a single File separately & correctly? 我是否单独和正确地将这三个Object写入单个文件中?
  3. Last but not least, How should I retrieve these above said all 3 Object through ObjectInputStream from "abcd.dat" File ? 最后但并非最不重要的, 我应该如何从"abcd.dat" File检索上述所有3 Object通过ObjectInputStream

Please help. 请帮忙。

I have create a file with 3 single objects 我创建了一个包含3个单个对象的文件

No. You have created a file with no objects and a whole lot of bytes, and no way of telling where one byte sequence stops and another starts. 没有。你创建了一个没有对象和大量字节的文件, 无法知道一个字节序列停止的位置和另一个字节序列的开始。 Use writeObject(), and read them with readObject() . 使用writeObject(),并使用readObject()读取它们。 The way you have it, there's no point in using ObjectOutputStream at all. 你拥有它的方式,根本就没有使用ObjectOutputStream

Note: appending to this file won't work. 注意:附加到此文件将不起作用。 See here for why. 这里是为什么。

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

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