FileSystemNotFoundException when launched from compiled jar
Paragoumba opened this issue · 4 comments
There is an error due to the fact that textures are in the jar and stb wants absolute paths. In the following code:
URL url = Texture.class.getResource("/textures/heightmap.png");
// Crashes
File file = Paths.get(url.toURI()).toFile();
The function Paths.get(URI) throws an FileSystemNotFoundException.
The same problem is present in the Texture class.
The program launches very well in IntelliJ IDEA since it does not build a jar, but if you use Maven to build one and launch it, it crashes.
Also encountered this problem yesterday.
A simple solution in this case would be to manually read the file from resources and load the texture from memory.
Example from Texture loading:
byte[] resourceData;
try (InputStream in = Texture.class.getResourceAsStream(fileName)) {
resourceData = in.readAllBytes();
}
ByteBuffer dataBuf = MemoryUtil.memAlloc(resourceData.length);
dataBuf.put(resourceData).flip();
buf = stbi_load_from_memory(dataBuf, w, h, channels, 4);
MemoryUtil.memFree(dataBuf);
You both are right, but I think this is explanied in the book. STB needs file paths, the reason I use relative classpath references is for convenience. Theses assets are expected to be placed outside the jar. STB will not ever be able to fetch them from a JAR.
In order to simplify this and avoid confussions. I was thinking on loading all the assets directly from the file systems instead of relaying on the classpath loader. What do you think on this?
One way that is... a bit less simple, but would work for different scenarios, and might be interesting for the readers of the book to copy for their own projects:
include the textures in the jar, and when running Main
, and they are not found on the filesystem, ask if the user wants to extract them there, or extract them automatically.
this would probably need looking for the textures in two paths, namely /src/main/resources/textures/
and just /textures/
, or alternatively, making /textures
a symbolic link to /src/main/resources/textures/
in the development repo.