简体   繁体   中英

How to read a excel file from src/test/resources in Java

I am trying to read an excel file for testing from test/resources, but i keep getting the FileNotFoundException . I have tried these two approaches, both seem to be giving the same FileNotFoundException .

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

You can try this:

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

This should get the file based upon the ClassLoader as long as the test directory is in your src folder. This will get the InputStream for the file.

*********************************UPDATE************************************ For File object:

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

I'm not sure what exactly you want do with this file but for Microsoft Office files I like to use 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM