簡體   English   中英

使用ObjectOutputStream將列表中的對象寫入文件

[英]Write Object from List to File, using ObjectOutputStream

我正在嘗試使用ObjectOutputStream將列表(對象)的內容寫入磁盤。

這是相關代碼:

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

這段代碼創建了一個名為emb.xlsx的文件,但是內容不是我所期望的。 如果我嘗試使用記事本打開,則類似於:

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

我在這里做錯了什么? 謝謝你的幫助。

我在這里做錯了什么?

您做錯了幾件事:

  1. 您正在將.xlsx擴展名誤用於序列化對象的文件。 該擴展名適用於XML格式的Excel電子表格。 您應該使用.bin.data.ser等。
  2. 當您應該使用POI內置的I / O設施時,就在使用序列化。
  3. 您正在嘗試使用文本編輯器讀取二進制文件。
  4. 您在close()之前多余地調用了flush() close()

如果其他人正在嘗試與我相同的操作,請使用以下代碼(有效!):

HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(InputStream);

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

不要嘗試將嵌入的對象放入列表中。 只需使用.write() :-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM