3

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,

  1. String
  2. String
  3. File ( size is between [1 to 1.5]GB )

Below is my code whichever I have used to write the 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.
  2. Am I writing these three Object inside a single File separately & correctly?
  3. Last but not least, How should I retrieve these above said all 3 Object through ObjectInputStream from "abcd.dat" File?

Please help.

user207421
  • 305,947
  • 44
  • 307
  • 483

1 Answers1

2

I have create a file with 3 single objects

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(). The way you have it, there's no point in using ObjectOutputStream at all.

Note: appending to this file won't work. See here for why.

Community
  • 1
  • 1
user207421
  • 305,947
  • 44
  • 307
  • 483
  • I have followed you suggestion and now when I am casting the `String str1 =(String)objInputStream.readObject()` then only first string is getting assigned and for file `File file =(File)objInputStream.readObject()' and this is working. I tried `ArrayList serializedObjectsList = (ArrayList) oi.readObject();` but getting class cast exception. How to overcome this when we have more than one objects of same type and read all those objects seperately. If you could provide code sample, that would be great! :) – Aditya Singh Rajput Apr 28 '23 at 07:20