如何从Java中的src / test / resources读取excel文件

时间:2015-04-28 14:55:42

标签: java excel file file-io

我正在尝试从test / resources中读取excel文件进​​行测试,但我一直在获取FileNotFoundException。我尝试了这两种方法,似乎都给出了相同的FileNotFoundException

File decisionConfig=new File("src/test/resources/mapping.xls");
File decisionConfig=new File("classpath:test/resources/mapping.xls");

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("test/resources/mapping.xls");

只要ClassLoader目录位于test文件夹中,就应该根据src获取文件。这将获得文件的InputStream

********** UPDATE ************* *********************** 对于File对象:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
File file = new File(classLoader.getResource("test/resources/mapping.xls").toString());

答案 1 :(得分:1)

我不确定您要对此文件做什么,但对于Microsoft Office文件,我喜欢使用Apache POI https://poi.apache.org/

FileInputStream file = new FileInputStream(new File("test/resources/mapping.xls"));

//Get the workbook instance for XLS file 
HSSFWorkbook workbook = new HSSFWorkbook(file);

//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);