Write Object from List to File, using ObjectOutputStream
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.
What am I doing wrong here?
You are doing several things wrong:
- 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.
- You are using Serialization when you should be using the I/O facilities built into POI.
- You are trying to read a binary file with a text editor.
- You are redundantly callling flush() before close().
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. :-)