0

I'm trying to write the content of a list (object) to disk using ObjectOutputStream.

This is the relevant code:

//Input Filetype is .xlsx with an embedded File (also .xlsx), Output Filetype should be .xlsx (Type of embedded File)
//This code should save the embedded File to D:\\...

List<HSSFObjectData> extrList = new ArrayList<HSSFObjectData>();

HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(pPart.getInputStream());
extrList = embeddedWorkbook.getAllEmbeddedObjects();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\scan_temp\\emb.xlsx"));

oos.writeObject(extrList);
oos.flush();
oos.close();

This code creates a file called emb.xlsx, but the content is not what I expected. If I try to open using notepad, it's something like:

¬í sr java.util.ArrayListxÒ™Ça I sizexp    w    x

What am I doing wrong here? Thanks for any help.

2 Answers 2

4

What am I doing wrong here?

You are doing several things wrong:

  1. You are misusing the .xlsx extension for a file of serialized objects. That extension is for Excel spreadsheets in XML format. You should use something like .bin, .data, .ser, etc.
  2. You are using Serialization when you should be using the I/O facilities built into POI.
  3. You are trying to read a binary file with a text editor.
  4. You are redundantly callling flush() before close().
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answer. So if my data is stored as binary file.. Is it even possible to save the embedded file (xlsx) in its original data format using ObjectOutputStream? Can you show me a sample code how to do it? Thank you very much!
ObjectOutputStream doesn't store anything 'in its original format'. It stores it according to a serialization protocol defined in the Object Serialization Specification. You need to have another look at the POI API for how to store spreadsheet objects as .xlsx. Serialization will not do it for you.
Okay, I just realised that my code was wrong in every way. :) ObjectOutputStream doesn't help in my case.
1

If anyone else is trying the same thing as I did, use the following code (works!):

HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(InputStream);

FileOutputStream fileOut = new FileOutputStream("/outputfilepath.xls");
embeddedWorkbook.write(fileOut);
fileOut.close();

Don't try to get the embedded objects into a list. Just use .write()and that's all. :-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.