Creating a URL object with a relative path

I am creating a Swing application with JEditorPane, which should display an HTML file called url1.html stored locally in the page folder in the project root folder.

I created an instance of the following String object

final String pagePath = "./page/"; 

and to display in the JEditorPane, I 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

There seems to be something wrong with creating url1. Does anyone know a solution to this problem?

+4
source share
3 answers

The solution is to find the absolute path to url1.html to make a java.io.File object on it, and then use the combination toURI().toURL() :

 URL url1 = (new java.io.File(absolutePathToHTMLFile)).toURI().toURL(); 

Assuming the current directory is the root of the page , you can pass the relative path to the 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 it will depend on where you start the application from. I would do this by taking the root directory as a command line argument if it is the only custom option for the application or from the configuration file, if any.

Another solution is to place the html file as a resource in your application's jar file.

+14
source

To load a resource from the classpath (as mentioned in khachik), 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 above case, using the Maven structure, the HTML page will be in this place:

 C:/myProject/src/main/resources/page/url1.html 
+1
source

I would try the following

 URL url = new URL("file", "", pagePath+"url1.html"); 

I believe that by concatenating the whole chain, you run into problems. Let me know if this helps.

0
source

All Articles