【发布时间】:2014-08-21 07:10:46
【问题描述】:
我有一个使用 Apache POI 库读取 excel 表的方法。为了使该方法通用,我需要在 catch 块中编写一些代码。方法如下:
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;
}
所以这里发生的事情是我不知道我正在提供什么类型的文件。我是根据上面给出的 try/catch 块来决定的。那么是否有任何通用的方法来决定使用哪个工作簿?由于上述代码在 catch 块中编写了流控制逻辑,因此这是一种不好的做法。
【问题讨论】:
-
这完全取决于错误条件是什么,以及方法的工作是什么。看看这个:stackoverflow.com/questions/465953/…
-
拥有 try-catch 块并不一定是坏事!我不明白这一点。发布一些显示您的问题的代码!
-
@isnot2bad 贴出代码!查看编辑!
-
你不能简单地检查文件扩展名吗?
-
是不是有可能用户将其命名为xls文件但文件格式为xlsx?
标签: java coding-style apache-poi