MalformedURLException when loading an HTML file from system

1.7k views Asked by At

So I'm working on a browser (just cause) and I keep getting a java.net.MalformedURLException. I'm trying to set a JEditorPane's page to a file which is loaded off of my computer. Here's the code:

  public Browser() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(500, 500);
    URLField = new JTextField("Enter the full address of the website:");
    displayWindow = new JEditorPane();
    try {
        homeURL = new URL(getCurrentDirectory() + "/resources/home.html");
        displayWindow.setPage(homeURL);
    } catch (IOException e) {
        e.printStackTrace();
    }
    tabs = new JTabbedPane();
    tabs.addTab("Home", displayWindow);

    add(URLField, BorderLayout.PAGE_START);
    add(displayWindow, BorderLayout.CENTER);
}  

And here's the error I get:

java.net.MalformedURLException: unknown protocol: x
    at java.net.URL.<init>(Unknown Source)
    at java.net.URL.<init>(Unknown Source)
    at java.net.URL.<init>(Unknown Source)
    at net.sourceforge.whowantsakookie.browser.Browser.<init>(Browser.java:25)
    at net.sourceforge.whowantsakookie.browser.Browser.main(Browser.java:42)

The lines it's referring to are line 25 and 42.
Line 25:

homeURL = new URL(getCurrentDirectory() + "/resources/home.html");

Line 42:

Browser browser = new Browser();

Thanks in advance!

2

There are 2 answers

1
Andrew Thompson On BEST ANSWER
  1. Establish a File object.
  2. Check it exists (sanity check).
  3. URL url = file.toURI().toURL();

Note that doing it this way will ensure that things like space chars in the file name/path are correctly encoded.

1
mtk On

Looks like you are not entering the string 'http://' before the url you are providing in the JTextField. Please check.