简体   繁体   English

getResourceAsStream 为现有文件返回 null

[英]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");但是.getResourceAsStream("/Me/my_txt.json"); returns null返回空值

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

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. class.getResource 在相对路径时从该类的包目录路径开始,或者绝对路径需要起始斜杠。

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.其中 ClientSecretsUtil 在同一个 jar 中。

Look in the jar (is in zip format), and check the path.查看 jar(是 zip 格式),并检查路径。 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.您的目录约定遵循 maven 构建基础结构,所以我的猜测可能是意外的 my_txt.json.txt 之类的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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