Reputation: 5801
I am accessing a Java resource to use in my JavaFX application..
URL resource = getClass().getClassLoader().getResource("/image.jpg");
File file = new File(resource.getFile());
if (!file.exists()) {
throw new FileNotFoundException("No image: " + file)
}
Everything works fine and the resource is found when running as the Java application.
However, now I am bundling my JavaFX application in a native Mac app using zenjava's Maven plugin:
<plugin>
<groupId>com.zenjava</groupId>
<artifactId>javafx-maven-plugin</artifactId>
<version>2.0</version>
<configuration>
<mainClass>
com.seaniscool.foobar.FooBar
</mainClass>
</configuration>
</plugin>
I build with the native plugin using:
mvn clean jfx:native
Now, when I run the application by running the Mac .app
file, this resource can no longer be resolved to a file. getResource
returns this URL:
jar:file:/Projects/foobar/target/foobar.app/Contents/Java/foobar-jfx.jar!/image.jpg
But it cannot be found when used as a File
path.
Upvotes: 3
Views: 1366
Reputation: 280138
The URL
in
URL resource = getClass().getClassLoader().getResource("/image.jpg");
is a uniform resource locator
. In this case it locates the resource identified by /image.jp
in a .jar
file. Which, as it turns out, is a type of zip
file.
jar:file:/Projects/foobar/target/foobar.app/Contents/Java/foobar-jfx.jar!/image.jpg
A zip entry is not a file, it's just a bunch of bytes that have some meaning to a zip file. If you want to get those bytes as an InputStream
, inflated, you can simply call
InputStream inputStream = resource.openStream();
See the javadoc of URL#openStream()
.
Upvotes: 1
Reputation:
You must use the fully qualified name meaning : /package1/package2/.../file-name
not /file-name
directly
Upvotes: 0