JMK
JMK

Reputation: 239

Improvement of reading and writing an Excel file[POI,Java]

is there any possibility to improve reading and writing to an excel file using POI library and Java? Right now my code looks like this:

//Reading a file
FileInputStream fin = new FileInputStream(new File(localizationOfExcelFile));
Workbook workbook = new XSSFWorkbook(fin);

//Writing to a file
FileOutputStream fout = new FileOutputStream(new File(localizationOfExcelFile));
workbook.write(fout);
fout.close();

Thanks a lot in advance!

Upvotes: 0

Views: 1601

Answers (1)

IceArdor
IceArdor

Reputation: 2041

If you're writing to a high-latency system (such as a networked hard drive), you should buffer your output with a BufferedOutputStream. I improved write times by an order of magnitude with the buffered write to a networked hard drive on Windows, while incurring a negligible penalty for buffering my writes to a local hard drive. Performance may vary depending on hard drive write caching, OS, and latency, so don't optimize for just your setup if others will be using your application.

Buffer your input with BufferedInputStream if it helps, though I didn't experience improvement in my test. As @Gagravarr suggested, try opening the workbook with File instead of FileInputStream.

If you do not know if you're opening an Excel 97-2003 or an Excel 2007+ file (don't guess based on file extension; a guess based on the first few bytes of the file is superior), use WorkbookFactory.create, though you would need to use a FileInputStream to avoid a bug that modifies the workbook when you close the workbook (even without saving).

It's good practice to close your streams (fin!) when you're done with them. Not sure if leaving the Streams open has an impact on memory, system file handle resources, or garbage collection, but it might help. Main thing is readability: you're making it clear that you're done with the Stream object.

Finally, hide implementation details whenever possible, even locally. Use OutputStream fout = new FileOutputStream(...) over FileOutputStream fout = ... whenever possible. Java is verbose: type declaration is defining a contract that the variable abides to. Instantiation chooses the implementation that will fulfill that contract.

Upvotes: 2

Related Questions