I am trying to get a java gui to open a web page. So the gui runs some code that does things and then produces a html file. I then want this file to open in a web browser (preferrably Firefox) as soon as it is created. How would I go about doing that?
If you're using Java 6 or above, see the Desktop API, in particular browse. Use it like this (not tested):
// using this in real life, you'd probably want to check that the desktop
// methods are supported using isDesktopSupported()...
String htmlFilePath = "path/to/html/file.html"; // path to your new file
File htmlFile = new File(htmlFilePath);
// open the default web browser for the HTML page
Desktop.getDesktop().browse(htmlFile.toURI());
// if a web browser is the default HTML handler, this might work too
Desktop.getDesktop().open(htmlFile);
Otherwise the JDIC libraries are a backport of the desktop functionality.
I've used BrowserLauncher2 with success. It'll invoke the default browser on all platforms tested. I use this for demoing software via JNLP. The software downloads, runs and drives the user's browser to information pages/feedback etc.
JDK 1.4 and above, I believe.
Ya, But if u want to open the webpage in your default web browser by a java program then u can use this code.
/// file OpenPageInDefaultBrowser.java
public class OpenPageInDefaultBrowser {
public static void main(String[] args) {
try {
//Set your page url in this string. For eg, I m using URL for Google Search engine
String url = "http://www.google.com";
java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
}
catch (java.io.IOException e) {
System.out.println(e.getMessage());
}
}
}
/// End of file
You can try to start a new process, as win+r does with the url as argument.
On my box, win+r "http://www.google.com"
opens google in firefox, Process.Start()
in C# does the same. Cant test javas Runtime.getRuntime().exec("http://www.google.com");
until I get on my home desktop.
Note: this may not work on all windows versions and I'm almost certain that this does not work with linux. I only want to supply an alternative here, in some cases this solution may be "good enough".