how to access resources(Excel file) in jar file

爱⌒轻易说出口 提交于 2019-11-29 15:07:14

I tried this and it is working for me.

My Test1 class is in default package, just check where your accessing class is in any package, if it is then go back to exact resource folder from classpath like this "../"

public class Test1 {

    public static void main(String[] args) {
        new Test1();  
    }
    Test1(){
        BufferedInputStream file= (BufferedInputStream) this.getClass().getResourceAsStream("resources/a.txt");
        try {
            System.out.println((char)file.read());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
Ted

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

A4L

I bet you have no package called resources in your project.

Trying to use Class.#getResourceAsStream is the way to go. But this method does not return a FileInputStream. It returns an InputStream wich is an interface.

You should be passing the absolute name of the resource

InputStream is = getClass().getResourceAsStream("my/pack/age/Excel.xlsx");

where the excel file is located in the directory

resources/my/pack/age

FileInputStream file= (FileInputStream) this.getClass().getResourceAsStream("/resources/Excel.xlsx");

Why do you need FileInputStream? Use

InputStream is = getClass().getResourceAsStream..

Secondly use "resources/Excel.xlsx" Thirdly when constructing file like this

new File(System.getProperty("user.dir")+File.separator+"resources"+File.separator+"Excel.xlsx"));

is hard to control slashes. use

new File("parent (userdir property)", "child (resources\Excel.xlsx)")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!