Search code examples
javaembedded-resourceexecutable-jar

Include excel in executable .jar file


I have to read data from an excel file and show the data in my application. I want to package my excel file (data file) along with the executable jar. I have created a source folder within my main project folder and named it 'res'. Inside 'res', I have 2 sub-folders (normal folders) called "images" and "data". Inside the data folder I have placed the excel file.

My Project Structure

project structure

Build Path

build path of project

Export as JAR

enter image description here

Problem:

The application works flawlessly when I run it from Eclipse but when I export it as a jar, the application doesn't work.It is able to find the images but fails to find the excel file.

In other-words, when I run the application from inside eclipse (Right Click -> Run As -> Java Application) it runs perfectly. But when the launch the exported JAR file ("Tool.jar"), it fails to read the excel data.

Code to Read Excel

URL excelResources = getClass().getResource("/excel/data.xls");
File excel = new File(excelResources.toURI());
FileInputStream fis = new FileInputStream(excel);

Solution

  • This...

    URL excelResources = getClass().getResource("/excel/data.xls");
    File excel = new File(excelResources.toURI());
    FileInputStream fis = new FileInputStream(excel);
    

    Is not how embedded resources work. You can no longer access the excel file as if it was a file on the file system, because it's not, it's embedded inside the Jar file.

    If you need an InputStream, use Class#getResourceAsStream

    try (InputStream is = getClass().getResourceAsStream("/excel/data.xls")) {
        //...
    } catch (IOException exp) {
        exp.printStackTrace();
    }