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 thecreated 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.