2013-12-11 65 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); 

除此之外,確保文件在您需要的瀏覽器已經打開。 檢查文件上的圖標,如果它顯示爲文本文件,則可能已經用文本文件打開。 因此,將默認程序更改爲所需的程序。