1

I am making a space shooter in Java, but when I try to load up the image resources, I get a null pointer exception. Everything works fine except the images. Am I coding the directory wrong? How can I fix it?

Here is my code:

BufferedReader highScoreReader;
BufferedWriter highScoreWriter;

try {
    playerImage = ImageIO.read(this.getClass().getResourceAsStream("src/res/player.png"));
    bulletImage = ImageIO.read(this.getClass().getResourceAsStream("src/res/bullet.png"));
    enemyImage = ImageIO.read(this.getClass().getResourceAsStream("src/res/enemy.png"));

    highScoreReader = new BufferedReader(new FileReader("/files/HIGH_SCORE.txt"));
    highScoreWriter = new BufferedWriter(new FileWriter("/files/HIGH_SCORE.txt"));
} catch (Exception e) {
    e.printStackTrace();
}

Here is a screenshot of my file directories:

enter image description here

3 Answers 3

2

Most probably, you need to copy your images into the build directory of your project. If you want them treated as classpath resources, which it seems you do, make sure they're in a source folder in eclipse (or, if you use maven or similar, in the src/main/resources folder. The point is, they need to be copied to the place where the .class file lives when it's running.

Remember: class.getResourceAsStream(...) returns things from the classpath not from your source path.

Sign up to request clarification or add additional context in comments.

Comments

0

I've never seen it done that way.

Try this

try {
    playerImage = ImageIO.read(getClass().getClassLoader().getResourceAsStream("src/res/player.png"));
catch(IOException e) {
}

or

try {
    playerImage = ImageIO.read(new File("src/res/player.png"));
catch (IOException e) {
}

7 Comments

I tried this and it didn't work Are there any other problems?
Can you tell us what the error is? You never specified what the problem is. What are you doing with the images?
I am drawing them to a frame. When I am running the code, the images are throwing me a NPE. Everything but the images work correctly.
try removing "src" from your path to the images. Your FileReader manages to find it's files without it. And use the second method. Don't worry about getting it as a stream, just use ImageIO.read(new File(filepath))
I am still getting the error. Maybe its a glitch in eclipse.
|
0

Arnav Garg has discovered the problem.

When your code says something like: file("src/res/player.png") the file is not there, i.e. file.exists() will return false

Find out where java thinks the file is.

try using file.getAbsolutePath() and compare that to your directory structure.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.