2013-12-11 62 views
13

我尝试通过Java程序从本地(在我的系统中)打开HTML文件。我尝试了一些通过堆栈溢出获得的程序,但其工作量并不多。如何使用Java打开HTML文件?

对于E.G .:我有这个小的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(); 

任何解决方案或建议表示赞赏。

+0

*“如何在chrome中打开HTML文件..?”*为什么'Chrome'与用户的默认浏览器相反? –

回答

30

我宁愿使用默认浏览器

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

@RamonBoza:它似乎工作正常,谢谢。 –

+0

我没有否定你的问题,也不知道为什么有人这样做,你的问题是100%有效的,所以我投了票xD – RamonBoza

+1

如果用户已经为文件扩展名指定了“open with”那么这将不会打开浏览器,但用户已将其与......链接起来的程序。这根本不是解决方案! – thesaint

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); 

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