如何使用Java打开HTML文件?

25

我尝试通过Java程序打开本地(在我的系统中)的HTML文件。 我尝试了一些在stackoverflow上找到的程序,但它们并没有像预期的那样运行。

例如: 我有一个小的HTML文件。

<html>
  <head> 
    Test Application
  </head>
  <body>
     This is test application
  </body>
</html>

我的 Java 代码:

Runtime rTime = Runtime.getRuntime();
String url = "D:/hi.html";
String browser = "C:/Program Files/Internet Explorer/iexplore.exe ";
Process pc = rTime.exec(browser + url);
pc.waitFor();

非常感谢任何解决方案或建议。


1
如何在Chrome中打开HTML文件?为什么选择“Chrome”而不是用户的默认浏览器? - Andrew Thompson
3个回答

55

我更喜欢使用默认浏览器

File htmlFile = new File(url);
Desktop.getDesktop().browse(htmlFile.toURI());

我没有否定你的问题,也不知道为什么有人这样做,你的问题是完全有效的,所以我投了赞成票 xD - RamonBoza
1
如果用户为文件扩展名(例如“html”)分配了自定义的“打开方式”操作,则不会打开浏览器,而是会打开用户与之链接的程序... 这根本不是解决方案! - thesaint
URI uri = new URL(url).toURI(); Desktop.getDesktop().browse(uri); 使用文件对我没有起作用,使用URL似乎可以。 - Ravisha
@thesaint 这不是一个解决方案吗?从未规定过这样的要求。 - nikodaemus
如何在Mac上打开它? - SaiPawan

5

这里是一个优雅地失败的方法的代码。

请注意,字符串可以是一个 html 文件的位置。

/**
* If possible this method opens the default browser to the specified web page.
* If not it notifies the user of webpage's url so that they may access it
* manually.
* 
* @param url
*            - this can be in the form of a web address (http://www.mywebsite.com)
*            or a path to an html file or SVG image file e.t.c 
*/
public static void openInBrowser(String url)
{
    try
        {
            URI uri = new URL(url).toURI();
            Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
            if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE))
                desktop.browse(uri);
        }
    catch (Exception e)
        {
            /*
             *  I know this is bad practice 
             *  but we don't want to do anything clever for a specific error
             */
            e.printStackTrace();

            // Copy URL to the clipboard so the user can paste it into their browser
            StringSelection stringSelection = new StringSelection(url);
            Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
            clpbrd.setContents(stringSelection, null);
            // Notify the user of the failure
            WindowTools.informationWindow("This program just tried to open a webpage." + "\n"
                + "The URL has been copied to your clipboard, simply paste into your browser to access.",
                    "Webpage: " + url);
        }
}

0
URI oURL = new URI(url);
Desktop.getDesktop().browse(oURL);

除此之外,请确保文件已在您所需的浏览器中打开。 检查文件上的图标,如果它显示为文本文件,则可能已经使用文本文件打开。因此,请将默认程序更改为所需的程序。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接