-2

I have a method that reads an excel sheet using Apache POI library. To make that method generic, I need to to write some code in a catch block. Here's the method:

private List<String[]> readFile(String filePath) throws IOException{
        List<String[]> sheetValues = new ArrayList<String[]>();
        //Two types of fileInputStreams for both the types of workbook i am about to use
        //
        FileInputStream fileInputStream = new FileInputStream(new File(filePath));
        FileInputStream fileInputStream2 = new FileInputStream(new File(filePath));
        LineItemFileReader fileReader = new LineItemFileReaderImpl();
        //If the file is in xls format i should use HSSFWorkbook
        //If the file is in xlsx format i should use XSSFWorkbook
        try {
        //If the file is in xlsx format then the below line will throw the
        //Exception and catch block code will be executed
            HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
            FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
            sheetValues = fileReader.ParseSheet(workbook.getSheetAt(1),evaluator);
        } catch (OfficeXmlFileException exception){
            XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream2);
            FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
            sheetValues = fileReader.ParseSheet(workbook.getSheetAt(1),evaluator);
        } finally{
            fileInputStream.close();
            fileInputStream2.close();
        }
        return sheetValues;
    }

So what's happening here is that I dont know what type of file I am being supplied. I am deciding that on the basis of the try/catch block given above. So is there any generic way of deciding which workbook to use? Since the above code has flow control logic written in a catch block, it's a bad practice.

1 Answers1

1

Use WorkbookFactory.create(...) for opening the Workbook. It will create the appropriate subclass internally:

Workbook workbook = WorkbookFactory.create(new File(filePath));
// ...
workbook.close();
isnot2bad
  • 24,105
  • 2
  • 29
  • 50