简体   繁体   中英

MalformedURLException when loading an HTML file from system

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!

  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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM