0

I have used

File file = new File(Game.class.getResource("Tiles.txt").getFile())

to get the txt file from my resources folder and it works fine when inside the IDE but when building to a jar and running outside of the environment it throws file not found errors (which i saw through running in CMD).

I use a similar method to get all my images and sprite sheets:

BufferedImage loadedImage = ImageIO.read(Game.class.getResourceAsStream("EG.png"));

how do they differ in importing files and why is my path incorrect?

Error CMD gives: https://i.stack.imgur.com/4gEIZ.jpg

C:\Users\Taka\Desktop>java -jar ProjectC-Revamped.jar
java.io.FileNotFoundException: file:\C:\Users\Taka\Desktop\ProjectC-Revamped.jar!\Tiles.txt (The filename, directory name, or volume label syntax is incorrect)
        at java.io.FileInputStream.open0(Native Method)
        at java.io.FileInputStream.open(Unknown Source)
        at java.io.FileInputStream.<init>(Unknown Source)
        at java.util.Scanner.<init>(Unknown Source)
        at Tiles.<init>(Tiles.java:16)
        at Game.<init>(Game.java:91)
        at Game.main(Game.java:192)
java.io.FileNotFoundException: file:\C:\Users\Taka\Desktop\ProjectC-Revamped.jar!\Maps\Map.txt (The filename, directory name, or volume label syntax is incorrect)
        at java.io.FileInputStream.open0(Native Method)
        at java.io.FileInputStream.open(Unknown Source)
        at java.io.FileInputStream.<init>(Unknown Source)
        at java.util.Scanner.<init>(Unknown Source)
        at Map.<init>(Map.java:20)
        at Game.<init>(Game.java:94)
        at Game.main(Game.java:192)
matvey-tk
  • 641
  • 7
  • 18

2 Answers2

1

use getResourceAsStream() instead of getResource(): see this SO answer for details

TmTron
  • 17,012
  • 10
  • 94
  • 142
0

URL.getFile() does not convert a URL to a file. It merely returns the path and query portions of the URL. The method is named getFile() only because the URL class was part of Java 1.0, which was released in 1995, back when most URLs happened to point to actual files.

The path returned by URL.getFile() returns a String which may or may not be a valid file path. Many characters may not legally appear in URLs, so they will be percent-escaped. A good example is spaces; for example, file:///C:/Program%20Files/Java.

In short, converting a URL to a file using getFile() is not safe and will eventually fail.

Also, an entry in a .jar file is not a file. A .jar file is a single archive file. Its entries are just subsequences of bytes (representing compressed data). On the other hand, the URL returned by getResource is always valid (assuming it’s not null), even if it represents a .jar entry.

VGR
  • 40,506
  • 4
  • 48
  • 63