Denis Rozimovschii
Denis Rozimovschii

Reputation: 448

Accessing resources in a Java[Maven] Project

Once and for all somebody, explain how to correctly access resources like DATABASE, HTML files and so on.

Suppose my Maven JavaFX project looks something like this (check the image).

http://s30.postimg.org/lacoynzv5/image.png

It has it's

src/main/java

and

src/main/resources

in the Build Path

Build path

Inside resources I have a folder with a database and a folder with a html file.

Here is how I access the database and it works when I run it inside the IDE, but doesn't work after packaging or running the .exe file after mvn native

Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:src/main/resources/DB/SeeYourUse.sqlite");

Here is how I access my HTML file to use it in a WebView

String url = Main.class.getResource("/HTML/help.html").toExternalForm();  
webEngine.load(url);

And it DOES work inside the IDE (jfx:run and running as java application as well), but not a chance to run it after the deployment.

Here is the error I get when I run it and log it.

java.sql.SQLException: path to 'src/main/resources/DB/SeeYourUse.sqlite': 'E:\Programming\Java\Work\SeeYourUse\target\jfx\native\SeeYourUse-0.0.1-SNAPSHOT\app\src' does not exist

The QUESTION is: How do I properly load the database and the HTML to be able to use it at maximum?

Upvotes: 4

Views: 6958

Answers (1)

Michał Zegan
Michał Zegan

Reputation: 466

src/main/resources is copied into your jar file directly, as is target/classes. You are able to access resources by class.getResource(String name) that returns the URL of a resource, and also Class.getResourceAsStream(String name) that will open a stream. But, in your specific case of a database, I would NOT put resources in a jar file as a jdbc driver loads database files directly from filesystem. You should extract a database to an external location by opening a stream to it and writing it to an external directory, at least if it does not exist already.

As for html files, you can retrieve URL's in case of such static resources and use them directly as noted above. Note however that the web engine will be unable to use other resources referenced from a html file, unless you can replace the logic that it uses to find them. In a case of such things, I would even extract the html file and all files it depends on into a temp location.

Upvotes: 3

Related Questions