getResourceAsStream returns null

前端 未结 16 2325
臣服心动
臣服心动 2020-11-22 04:00

I\'m loading a text file from within a package in a compiled JAR of my Java project. The relevant directory structure is as follows:

/src/initialization/Life         


        
相关标签:
16条回答
  • 2020-11-22 04:30

    What worked for me was to add the file under My Project/Java Resources/src and then use

    this.getClass().getClassLoader().getResourceAsStream("myfile.txt");
    

    I didn't need to explicitly add this file to the path (adding it to /src does that apparently)

    0 讨论(0)
  • 2020-11-22 04:35

    So there are several ways to get a resource from a jar and each has slightly different syntax where the path needs to be specified differently.

    The best explanation I have seen is this article from InfoWorld. I'll summarize here, but if you want to know more you should check out the article.

    Methods

    1. ClassLoader.getResourceAsStream().

    Format: "/"-separated names; no leading "/" (all names are absolute).

    Example: this.getClass().getClassLoader().getResourceAsStream("some/pkg/resource.properties");

    1. Class.getResourceAsStream()

    Format: "/"-separated names; leading "/" indicates absolute names; all other names are relative to the class's package

    Example: this.getClass().getResourceAsStream("/some/pkg/resource.properties");

    Updated Sep 2020: Changed article link. Original article was from Javaworld, it is now hosted on InfoWorld (and has many more ads)

    0 讨论(0)
  • 2020-11-22 04:36

    You might want to try this to get the stream i.e first get the url and then open it as stream.

    URL url = getClass().getResource("/initialization/Lifepaths.txt"); 
    InputStream strm = url.openStream(); 
    

    I once had a similar question: Reading txt file from jar fails but reading image works

    0 讨论(0)
  • 2020-11-22 04:36

    Don't know if of help, but in my case I had my resource in the /src/ folder and was getting this error. I then moved the picture to the bin folder and it fixed the issue.

    0 讨论(0)
  • 2020-11-22 04:40

    Lifepaths.class.getClass().getResourceAsStream(...) loads resources using system class loader, it obviously fails because it does not see your JARs

    Lifepaths.class.getResourceAsStream(...) loads resources using the same class loader that loaded Lifepaths class and it should have access to resources in your JARs

    0 讨论(0)
  • 2020-11-22 04:40

    What you really need is a full absolute classPath for the file. So instead of guessing it, try to find out the ROOT and then move the file to a better location base one <.war> file structures...

    URL test1 = getClass().getResource("/");
    URL test2 = getClass().getClassLoader().getResource("/");            
    URL test3 = getClass().getClassLoader().getResource("../");
    
    logger.info(test1.getPath()); 
    logger.info(test2.getPath());
    logger.info(test3.getPath());
    
    0 讨论(0)
提交回复
热议问题