I'm working on Java project and I have a little problem.
My project is currently runnable and works correctly when i launch him from IntelliJ. To work, he needs some resources like images or .txt files.
This is my current file configuration
My problem is:
When I export the project in executable jar file, he doesn't work. The reason is that he cannot find the resources.
However, I have used Class.class.getResourcesAsStream(String)
.
The most curious is that resources are in the jar, and correctly placed...
Anyone can help us ?
Thanks for your help.
My Code
File f = new File(Loader.class.getResource("/xsbfiles").getFile());
System.out.println(f.getAbsolutePath() +": exists ? " + f.exists());
System.out.println(f.getAbsolutePath());
Launching of the application from Intellij
/Users/gael/IdeaProjects/Sockoban/out/production/Sokoban/xsbfiles: exists ? true
/Users/gael/IdeaProjects/Sockoban/out/production/Sokoban/xsbfiles
Opening /Users/gael/IdeaProjects/Sockoban/out/production/Sokoban/xsbfiles/MicroCosmos.txt
Successful Opening
Launching of the jar file from terminal
/Users/gael/IdeaProjects/Sockoban/out/artifacts/Sokoban/file:/Users/gael/IdeaProjects/Sockoban/out/artifacts/Sokoban/Sokoban.jar!/xsbfiles: exists ? false
/Users/gael/IdeaProjects/Sockoban/out/artifacts/Sokoban/file:/Users/gael/IdeaProjects/Sockoban/out/artifacts/Sokoban/Sokoban.jar!/xsbfiles
No xsbfile found
Edit:
Finally, I have solve my problem using BufferedReader like in the example:
BufferedReader reader = new BufferedReader(
new InputStreamReader(MyClass.class.getResourceAsStream("/xsbfiles/MicroCosmos.txt")));
This is a good solution to load one file. However, I need to read all files in the folder called xsbfiles...
I have searched in different sources and found a similar question.
An answer suggests to use a "hack" to list files contained in the folder. This is the example of code by Boris the Spider:
public static List<URL> getResources(final String path) throws IOException {
final ClassLoader loader = Thread.currentThread().getContextClassLoader();
try (
final InputStream is = loader.getResourceAsStream(path);
final InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
final BufferedReader br = new BufferedReader(isr)) {
return br.lines()
.map(l -> path + "/" + l)
.map(r -> loader.getResource(r))
.collect(toList());
}
}
To well understand the code, I have run him on my IDE and in the terminal. It's seems run correctly on my IDE but not with the jar.
What did I do that doesn't work ?