You do not need to get so involved with identifying whether you are working with a binary or OpenXML file youself, the WorkbookFactory class can do that for you;
http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/WorkbookFactory.html There is a static create() method that takes an InputStream, identifies the type of the file and then returns to you a Workbook object connected to that file. That should allow you to resolve many of the issues with your code. import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.OutputStream; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.ss.usermodel.WorkbookFactory; public class XLSXTester { public static void main(String [] args) { File file = null; FileInputStream fis = null; FileOutputStream fos = null; Workbook wb = null; try { file = new File(args[0]); fis = new FileInputStream(file); wb = WorkbookFactory.create(fis); // Not strictly necessary but I like to close and null the stream here fis.close(); fis = null; // Assuming you want to copy the file out using the same name fos = new FileOutputStream(file); wb.write(fos); } catch (Exception e) { e.printStackTrace(); } finally { if(fis != null) { try { fis.close(); fis = null; } catch(Exception ex) { // Nothing can be done now. } } if(fos != null) { try { fos.close(); fos = null; } catch(Exception ex) { // Nothing can be done now. } } } } } I have not tested this code but I think it will copy the files for you - of course it will use the same name. Yours Mark B yehogold wrote: > > Hi. > > I'm trying to update some code to work with both xls and xlsx workbooks. > Unfortunetly, the workbooks keep on getting corrupted when I write out the > workbooks. I've even made a simple tester program, attached, that just > reads in an .xlsx file and outputs it to the same file. After I run the > tester, the file is corrupted is much smaller in size and corrupted. What > am I doing wrong? > > Thank you for your help, > -yehogold > > http://www.nabble.com/file/p24956535/XLSXTester.java XLSXTester.java > -- View this message in context: http://www.nabble.com/Corrupted-xlsx-files-tp24956535p24957127.html Sent from the POI - User mailing list archive at Nabble.com. --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
