Dealing with getResourceAsStream for outside file

核能气质少年 提交于 2020-01-15 08:31:09

问题


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



来源:https://stackoverflow.com/questions/11345657/dealing-with-getresourceasstream-for-outside-file

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