tags:

views:

859

answers:

4

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?

+6  A: 

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.

Dan Vinton
great thanks never knew about this API
Paul Whelan
How is it you get it to work? I do: Desktop desktop;... desktop.browse("file:///H:/Individual%20Project/file%20for%20gui%20NEW.html");
The Special One
@TheSpecialOne - see the updated answer for a stab...
Dan Vinton
Hey. Still can't get it to work. I get the following error: "Error message: The system cannot find the path specified." This is even though I have given it the exact path.
The Special One
@TheSpecialOne - are you supplying a _local_ path to the file? eg: on a windows box, htmlFilePath would look like "c:\path\to\file.html". Don't use the URL syntax...
Dan Vinton
A: 

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.

Brian Agnew
+1  A: 

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
Ankur Pandya
A: 

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".

atamanroman