getResourceAsStream returns null

前端 未结 16 2551
臣服心动
臣服心动 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: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)

提交回复
热议问题