-1

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?

Elad Benda
  • 35,076
  • 87
  • 265
  • 471
  • What's the structure of your project? How do you build it? How do you run it? – JB Nizet Nov 01 '17 at 15:09
  • `"/src/main/resources/Me/my_txt.json"` I run the java code via tomcat project in intelij – Elad Benda Nov 01 '17 at 15:26
  • Is it a Maven project? Have you imported it as a Maven project in IntelliJ? Is the src/main/resources folder marked as a Resources Root in IntelliJ? – JB Nizet Nov 01 '17 at 15:27
  • 1
    What does the Javadoc of that method say about how it resolves the resource name? – Sotirios Delimanolis Nov 01 '17 at 15:28
  • No maven. gradle. but it all works as I run it in intliji tomcat config. – Elad Benda Nov 01 '17 at 15:28
  • Then have you imported it as a gradle project? Is the src/main/resources folder marked as a Resources Root in IntelliJ? Why did you add a leading "/", which should not be there? – JB Nizet Nov 01 '17 at 15:30
  • yes, it's marked as resources. I added the `/` as a try. doesn't work with or without – Elad Benda Nov 01 '17 at 15:32
  • Possible duplicate of [What is the difference between Class.getResource() and ClassLoader.getResource()?](https://stackoverflow.com/questions/6608795/what-is-the-difference-between-class-getresource-and-classloader-getresource) – patrik Nov 01 '17 at 15:32

1 Answers1

0
  • 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.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138