Reputation:
I am writing simple application and I got kinda lost - here is the deal:
Project structure is as follows:
ProjectApp
|-- pom.xml
`-- .idea
`-- src
-- main
|-- java
| `-- myapp
| |-- components
| | <some files>
| |-- controllers
| | <some files>
| |-- repositories
| | <some files>
| |-- Main.java
`-- resources
|-- database
| -- Data.csv
`-- fxml
-- Scene.fxml
As you can see in the resources folder I have 2 subfolders, one of them is for data another one for fxmls (this app is simple JavaFX application). Now, here is the problem:
Code I use for loading scene
String SCENE_PATH = "/fxml/Scene.fxml";
Parent root = FXMLLoader.load(getClass().getResource(SCENE_PATH));
Code I use for loading data (I am using opencsv library)
String DATA_PATH = "database/ClientData.csv";
ClassLoader classLoader = getClass().getClassLoader();
File dataFile = new File(classLoader.getResource(DATA_PATH).getFile());
CSVReader reader = new CSVReader(new FileReader(clientDataFile));
I hope I am providing enough context here, if not, please let me know and I will edit (pom.xml is very basic, nothing fancy there). Now, this WORKS under IntelliJ, but when I try to run it with maven, like:
mvn clean package
java -cp ./target/ProjectApp.jar myapp.Main
from ProjectApp directory, application runs, but I get FileNotFoundException (it loads fxml files, but no csv files - i get working application, but without access to data). Also, why when accessing fxml files I must provide (NullPointerException if not) "/" at the beginning of the path, but when I am accessing csv files I must not do that (so path "/database/ClientData.csv" results in NullPointerException)?
@EDIT
Actually problem seemed to be with a packaging - when I package application to jar file, it adds exclamation mark to the path, so the path is incorrect (or at least I think so).
Upvotes: 0
Views: 957
Reputation: 3709
accessing csv files I must not do that (so path "/database/ClientData.csv" results in NullPointerException)
Because when you try to load resource from getClass().getClassLoader()
it doesn't take path starting with /
why when accessing fxml files I must provide (NullPointerException if not) "/" at the beginning of the path
Because if you do not provide the /
at the start of your file [fxml/Scene.fxml] it will tried to be located from the package of the class on which the method is called, which will be like myapp/controller/ClassName...
or so on, hence it will fail to load the resource.
But when you provide the /
at the start of your file [fxml/Scene.fxml] it will tried to be located from the root of the classpath, hence it is located succesfully
Upvotes: 1