Creating a URL object with a relative path
Asked Answered
O

3

6

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?

Om answered 22/11, 2010 at 16:34 Comment(0)
N
12

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.

Nympha answered 22/11, 2010 at 16:42 Comment(0)
M
1

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
Mcmillen answered 14/10, 2015 at 14:26 Comment(0)
C
0

I would try the following

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

I believe by concatenating the whole string, you are running into problems. Let me know, if that helped

Centuplicate answered 22/11, 2010 at 16:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.