I am creating a Swing application with a JEditorPane
that should display an HTML file named url1.html
stored locally in the page folder in the root folder of the project.
I have instantiated the following String object
final String pagePath = "./page/";
and in order to be displayed by the JEditorPane
pane I have created the following URL object:
URL url1 = new URL("file:///"+pagePath+"url1.html");
However when the setPage()
method is called with the created URL object as a parameter:
pagePane.setPage(url1);
it throws me a java.io.FileNotFoundException
error.
It seems that there is something wrong with the way url1
has been constructed. Anyone knows a solution to this problem?
The solution is to find an absolute path to url1.html
make an object of java.io.File
on it, and then use toURI().toURL()
combination:
URL url1 = (new java.io.File(absolutePathToHTMLFile)).toURI().toURL();
Assuming if the current directory is the root of page
, you can pass a relative path to File
:
URL url1 = (new java.io.File("page/url1.html")).toURI().toURL();
or
URL url1 = (new java.io.File(new java.io.File("page"), "url1.html")).toURI().toURL();
But this will depend on where you run the application from. I would make it taking the root directory as a command-line argument if it is the only configurable option for the app, or from a configuration file, if it has one.
The another solution is to put the html file as a resource into the jar file of your application.
To load a resource from the classpath (as khachik mentioned) you can do the following:
URL url = getClass().getResource("page/url1.html");
or from a static context:
URL url = Thread.currentThread().getContextClassLoader().getResource("page/url1.html");
So in the case above, using a Maven structure, the HTML page would be at a location such as this:
C:/myProject/src/main/resources/page/url1.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With