Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a URL object with a relative path

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?

like image 593
Anto Avatar asked Nov 22 '10 16:11

Anto


2 Answers

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.

like image 141
khachik Avatar answered Oct 18 '22 11:10

khachik


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
like image 33
jcadcell Avatar answered Oct 18 '22 13:10

jcadcell