Open an HTML File Inside a .JAR File

混江龙づ霸主 提交于 2019-12-12 12:06:12

问题


I have an html file called snake.html that I would like to put inside a jar. When the jar is run the main class should open this html file in the browser. I have tried:

public static void main(String[] args) throws IOException, URISyntaxException {
    URL url = Snake.class.getResource("/WebContent/snake.html");
    System.out.println(url);
    // relative to the class location
    Desktop.getDesktop().browse(url.toURI());
}

Which works if I just run this code but when I jar it (and the html file) I get the following exception:

Exception in thread "main" java.io.IOException: Failed to mail or browse
       jar:file:/Users/~user~/Desktop/Snake%20v0.1.jar!/WebContent/snake.html. 
       Error code: -10814
at apple.awt.CDesktopPeer.lsOpen(CDesktopPeer.java:52)
at apple.awt.CDesktopPeer.browse(CDesktopPeer.java:45)
at java.awt.Desktop.browse(Desktop.java:368)
at snake.Snake.main(Snake.java:26)

Im wondering if I have a classpath issue or maybe Im not directing the jar to the file correctly. THe jar has two directories, snake and WebContent. Snake has the snake.class file and WebContent has snake.html.

Any and all help/criticism appreciated.


回答1:


You'll have to devompress the file first.

Something like:

public static void main(String[] args) throws IOException, URISyntaxException {
    URL url = Snake.class.getResource("/WebContent/snake.html");


    File temp = File.createTempfile();
    temp.deleteOnExit();

    // Copy content 

    Desktop.getDesktop().browse(temp.getAbsolutePath());
}



回答2:


(HTML) ..inside a jar. When the jar is run the main class should open this html file in the browser.

Browsers are not designed to display HTML inside Java archives. Java components like JEditorPane can. If the HTML renders to your satisfaction inside a Swing component, use that. Otherwise it will be necessary to

  1. Locate the resource by URL.
  2. Extract it to a location on the local file-system.
  3. Use the browser to open the file (the easiest way is using Desktop.open(File)).



回答3:


Try to load the snake.html file like this:

ClassLoader.getSystemResource("/WebContent/snake.html");


来源:https://stackoverflow.com/questions/10185592/open-an-html-file-inside-a-jar-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!