我尝试通过Java程序从本地(在我的系统中)打开HTML文件.我尝试了一些程序通过堆栈溢出,但它没有工作.
对于EG:我有这个小HTML文件.
<html>
<head>
Test Application
</head>
<body>
This is test application
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我的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();
Run Code Online (Sandbox Code Playgroud)
任何解决方案或提示赞赏.
Ram*_*oza 41
我更喜欢使用默认浏览器
File htmlFile = new File(url);
Desktop.getDesktop().browse(htmlFile.toURI());
Run Code Online (Sandbox Code Playgroud)
以下是优雅失败的方法的代码.
请注意,字符串可以是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);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
50475 次 |
最近记录: |