简体   繁体   中英

getResourceAsStream returns null for an existing file

I try to load a resource file as a stream:

public static InputStream getClientSecretStream() {
    return ClientSecretsUtils.class.getClassLoader().getResourceAsStream("/Me/my_txt.json");
}

I have the file under:

"/src/main/resources/Me/my_txt.json"

But .getResourceAsStream("/Me/my_txt.json"); returns null

and .getResourceAsStream("my_txt.json"); returns null as well

what should I check for?

  • A class loader has absolute paths, without heading slash.
  • A class.getResource starts at the package directory path of that class when a relative path, or needs a starting slash for absolute paths.

So:

return ClientSecretsUtils.class.getClassLoader()
           .getResourceAsStream("Me/my_txt.json");
return ClientSecretsUtils.class.getResourceAsStream("/Me/my_txt.json");

Where ClientSecretsUtil is in the same jar.

Look in the jar (is in zip format), and check the path. It must be case sensitive .

Your directory convention adheres to the maven build infrastructure, so my guess is maybe an accidental my_txt.json.txt or such.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM