Dealing with getResourceAsStream for outside file

2019-07-09 08:58发布

问题:

I'm having a problem with getResourceAsStream method - it returns null because of wrong directory. The problem is that I do not have an idea how to define the dir.

My project structure looks like that

Project
  #src
    #com.package
      #ExampleClass.java
  #dll
    #MyFile.dll

When I have

InputStream in = this.getClass().getResourceAsStream("../dll/" + "MyFile.dll");

It returns null. Do anyone have an idea how to deal with this problem and how the path schould be defined?

回答1:

If this is ExampleClass in com.package package, you need to go two levels up to reach the root of the CLASSPATH:

this.getClass().getResourceAsStream("../../dll/" + "MyFile.dll");

Assuming /dll directory is placed directly in the root of your CLASSPATH. Or simply use absolute path:

this.getClass().getResourceAsStream("/dll/" + "MyFile.dll");

If the /dll/MyFile.dll is not on yout CLASSPATH (just open your JAR file and check whether it's there) you should use file system mechanisms to open it.



回答2:

It depends on location of MyFile.dll in classpath, not location of MyFile.dll onyour project. Please take a look at where to put a file to read from a class