Barış Doğa Yavaş
Barış Doğa Yavaş

Reputation: 83

Eclipse Reads From File But Runnable .jar File Doesnt

I'm making a simple game.

Eclipse reads a text file but when I export my project as runnable jar file it doesn't read it.

My resource folder looks like this: https://i.sstatic.net/LK2SF.png

The code:

 BufferedReader br = new BufferedReader(
   new FileReader("Resources/LevelManager/LevelManager.txt"));

When i run runnable jar file I get this error:

 java.io.FileNotFoundException: Resources\LevelManager\LevelManager.txt (System cant find the path)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.io.FileReader.<init>(Unknown Source)
    at LevelManager.Utils.getLevel(Utils.java:13)
    at LevelManager.LevelManager.<init>(LevelManager.java:15)
    at State.GameState.<init>(GameState.java:26)
    at Main.Game.init(Game.java:54)
    at Main.Game.run(Game.java:80)
    at java.lang.Thread.run(Unknown Source)`

Thank you for your answers.

Upvotes: 1

Views: 557

Answers (1)

fge
fge

Reputation: 121692

This is a classical error.

Your application will run in its own jar; which means its resources will be included in the jar and not available as File objects. You need to use a classloader.

I'm not sure how you intend to read from the resource but here is how to obtain a stream from a resource (and please note that slashes are used for separators, always:

@WillNotClose //this is a JSR 305 annotation
public static InputStream loadResource(final String resourcePath)
    throws IOException
{
    final URL url = EnclosingClass.class.getResource(resourcePath);
    if (url == null)
        throw new IOException(resourcePath + ": resource not found");
    return url.openStream();
}

Upvotes: 1

Related Questions