How to read a file from a java class, both are in the same jar

纵饮孤独 提交于 2020-01-04 05:50:12

问题


I have following structure in jar

myjar.jar -> com -> MYProgram.class

       -> file.txt

In MYProgram i am trying to do:

getClass().getResourceAsStream("../file.txt")

I am getting NullpointerException when i try to read the inputstream..

Where is it going wrong ?


回答1:


Either use

getClass().getResourceAsStream("/file.txt")

or

getClass().getClassLoader().getResourceAsStream("file.txt")

(ClassLoader.getResourceAsStream always takes an "absolute" resource name.)

I don't believe navigating up the "directory hierarchy" works in getResourceAsStream - the path either has to be relative to the given class but without navigating back up the tree, or it has to be absolute to start with.




回答2:


Try the absolute path:

getClass().getResourceAsStream("/file.txt")

The Javadoc for getResourceAsStream says:

  • If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
  • Otherwise, the absolute name is of the following form:

        modified_package_name/name
    

    Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').

This would turn your path into this absolute path:

/com/../file.txt

I don't think the .. notation is respected. It literally looks for the above absolute path.



来源:https://stackoverflow.com/questions/5476530/how-to-read-a-file-from-a-java-class-both-are-in-the-same-jar

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