I try to open HTML file from local (In my system) by Java program. I tried some of the program got through stack overflow but its not working as much.
For E.
Here is the code for a method that fails gracefully.
Note that the string can be the location of an html
file.
/**
* 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);
}
}
URI oURL = new URI(url);
Desktop.getDesktop().browse(oURL);
Apart from that, make sure that file is already opened in your desired browser. Check the icon on the file, If it is showing like a text file, you might have already opened with Text file. So change the default program to the desired program.
I would prefer to use default browser
File htmlFile = new File(url);
Desktop.getDesktop().browse(htmlFile.toURI());