1

I cannot seem to get java to pick up a resource file I have. Whenever I use the code snippet below, the stream is always null.

public void getPage() throws IOException {
    InputStream stream = Page.class.getResourceAsStream("/pages/test.html");
}

Project Strucutre

I am using JDK 12 and IntelliJ IDEA 2019.2.4. I've also tried "page/test.html" as the path.

Matthewj
  • 1,932
  • 6
  • 26
  • 37
  • Looks like Page is in a module. Is getPage a method that Page defines? Assuming it is, then `Page.class.getResourceAsStream("/pages/test.html)"` will try to locate the resource in Page's module. You screen shot seems to be the source layout, you'll need to show us the output directory to help with the question. I assume you don't have an issue when the classes and resources are packaged into a JAR file. – Alan Bateman Nov 07 '19 at 08:35

3 Answers3

0

check for Settings ▶ Build, Execution, Deployment ▶ Compiler ▶ Resource patterns.

The setting contains all extensions that should be interpreted as resources. If an extension does not comply to any pattern here, class.getResource will return null for resources using this extension.

Refer to https://stackoverflow.com/a/10723585/9020698

Mayank Pande
  • 150
  • 7
0

When you read files in Java, there are (at least) two ways to do so:

  • either from the filesystem as you would any normal file. You can give an absolute path (/home/username/file.txt) or a relative one. Relative paths are relative to where the program was run from. I tend to stay away from using relative paths.

  • or via classpath-based resources. This is what your code does. this.getClass().getResourceAsStream(...) takes an absolute classpath. If you have a file in your src/ folder called file.txt then its path would be /file.txt.

In your case, you need to make sure your resources folder is on the classpath. It'll then work.

David Brossard
  • 13,584
  • 6
  • 55
  • 88
  • I've added the resources folder to the classpath(I think) and I've even tried adding the HTML file to every single folder in the source directory, but it still doesn't pick it up. Originally, when I had the HTML file in the resources folder, the file would appear in /pages/index.html inside the jar file. – Matthewj Nov 02 '19 at 05:45
-2

You can use

public void getPage() throws IOException {
    InputStream stream = this.getClass().getResourceAsStream("pages/test.html");
}
Elgin
  • 95
  • 5