19

I'm aware there are several other questions regarding this...

But my problems seems to be a bit different because I seem to have all of the necessary things to NOT have this problem.

The code:

 this.getClass().getResource("checkstyle_whitespace.xml"); // null

The issue is that I've verified my classpath by inspecting the class loader in the debugger. Here's what I am seeing:

 27 = {URL@1235} "file:/Users/dennis/Documents/Development/java/java-grader/build/classes/main/"
 28 = {URL@1236} "file:/Users/dennis/Documents/Development/java/java-grader/build/resources/main/"

Blow is a quick tree of my directory structure. See build/resources and src/main/resources. The files are being copied when gradle builds my project.

├── build
│   ├── classes
│   │   ├── main
│   │   │   └── javaGrader
│   │   └── test
│   │       └── javaGraderTest
│   └── resources
│       └── main
│           ├── checkstyle_whitespace.xml
│           └── grammars
├── src
│   ├── main
│   │   ├── java
│   │   │   └── javaGrader
│   │   └── resources
│   │       ├── checkstyle_whitespace.xml
│   │       └── grammars
│   └── test
│       ├── java
│       │   └── javaGraderTest
│       └── resources
│           └── mini_test
├── target
│   ├── classes
│   ├── generated-sources
│   │   └── annotations
│   └── generated-test-sources
│       └── test-annotations
└── test_assets

From what I understand, the files should be accessible because they're in build. Correct me if I am wrong...

Community
  • 1
  • 1
djthoms
  • 3,026
  • 2
  • 31
  • 56

2 Answers2

24

If you pass a resource path that doesn't start with a / to Class.getResource(), the class loader looks for the resource in the package of the class. Not at the root. Your code should be

this.getClass().getResource("/checkstyle_whitespace.xml")

or

this.getClass().getClassLoader().getResource("checkstyle_whitespace.xml")
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • I'm using `ClassLoader.getSystemResourceAsStream("/Configuration.json")`. It was working, but after refreshing the project, it starting returning null. – Cardinal System Jun 20 '19 at 20:51
  • 1
    getClass().getClassLoader().getResource("FXMLDocument.fxml") and getClass().getClassLoader().getResourceAsStream("Picture.png") both methods worked but if you are using gradle then make sure to put those files (images and xml files) in the resources folder. Otherwise you may still get the null pointer – Sai Haridass Sep 13 '19 at 16:25
  • This works, but `checkstyle_whitespace.xml` should be placed in `/resources` folder. – vovahost Sep 02 '20 at 21:35
1

Create a folder called "resources" in the same Location that java folder exist in the main folder of the project. and locate all the images and other resources into the "resources" folder. the get those like this

new ImageIcon(getClass().getClassLoader().getResource("image.png"));
Lasitha Lakmal
  • 486
  • 4
  • 17