Apache POI - FileInputStream works, File object fails (NullPointerException)

后端 未结 2 618
深忆病人
深忆病人 2020-11-29 13:03

I try to copy all worksheets from one workbook to another workbook. The thing is, it works normally if I read the workbooks via FileInputStreams, but it does not work with F

2条回答
  •  时光取名叫无心
    2020-11-29 13:30

    Just stumbled across a potential solution to this issue. I'm no expert, so feel free to suggest alternatives or modifications to my method.

    I also encountered this issue, where the POI documentation advises using a File object rather than a FileInputStream, but fails to mention that the created Workbook cannot then be written to the original file to modify it.

    However, by creating a temporary copy of the original file using the nio.channels.FileChannel.transferFrom function of the later JDKs (As shown here Standard concise way to copy a file in Java?) I was able to read my data from the duplicated file and then write to the original using the regular workbook.write function.

    One caveat of this, is that the 'temporary' copy still cannot be deleted whilst it is being accessed. However, it apparently can still have data transferred to it. Once the jvm instance ends, the file can be deleted, so I am treating it like the temporary or backup documents that are sometimes created, for instance when modifying a Word document.

提交回复
热议问题