how to access resources(Excel file) in jar file

后端 未结 4 1566
Happy的楠姐
Happy的楠姐 2020-12-21 05:27

Hi i have exported my java project as executable jar file. inside my project I am accessing a Excel file containing some data. Now I am not able to access the Excel file whe

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-21 06:25

    The first step is to include the excel file itself in your project. You can create a resources folder like you show, but to make sure this gets included in your jar, you add the resources folder in along with your source code files so that it gets built into the jar.

    Then

    InputStream excelContent = this.getClass().getResourceAsStream("/resources/Excel.xlsx");
    

    should work. From one post at least, the leading forward slash may also mess things up if you use the ClassLoader.

    getClass().getResourceAsStream("/a/b/c.xml")  ==> a/b/c.xml
    getClass().getResourceAsStream("a/b/c.xml")  ==> com/example/a/b/c.xml
    getClass().getClassLoader().getResourceAsStream("a/b/c.xml")  ==> a/b/c.xml
    getClass().getClassLoader().getResourceAsStream("/a/b/c.xml")  ==> Incorrect
    

    ref: getResourceAsStream fails under new environment?

    Also in eclipse you can set the resources folder as a source folder like this:

    in the properties of your eclipse project, go to java build path, select sources, and check to see if all needed source fodlers are added (as source folders). If some are missing, just add them manually using add sources... button

    ref: Java Resources Folder Error In Eclipse

提交回复
热议问题