tags:

views:

65

answers:

3

Hi there

how to I open a URL with the systems standard browser with Java?

I currently use this code for opening a specific URL (locally stored html file), which works fine when I run the application with my IDE (Eclipse), but after bundling the software, it doesn't work any more.

    url = MainWindow.class.getResource("mySite.html");

    helpMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {    
            try {
                java.awt.Desktop.getDesktop().browse(url.toURI());
            }
            catch (URISyntaxException e1) {
                e1.printStackTrace();
            }
            catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    });

Any suggestsions? Thank you very much!

A: 

Any idea why it doesn't work? You can try JDIC, it has not been updated for a while but should do the trick.

Guillaume
+2  A: 

but after bundling the software, it doesn't work any more.

You cannot browse to URL's which points to resources inside a JAR file. You need to extract the resource (just get InputStream using getResourceAsStream()) and store it somewhere else (as temp file?) and then browse it instead.

BalusC
So I then have to convert the InputStream to a File, right?
Peter
No, take the file in your classpath and copy it to your file system somewhere (like as a temp file like BalusC suggested). Then, you can open the copy in a browser.
Michael Angstadt
No, just write it to an `OutputStream` the usual Java IO way, which can be `FileOutputStream`.
BalusC
Sorry for answering that late, but I still couldn't figure out what exactly I have to do.As suggested, I get the resource as an InputStream, like this:InputStream s = MainWindow.class.getResourceAsStream("mySite.html");But then what?
Peter
Store it as "loose" `File` at local disk file system and finally browse that instead. You can write `InputStream` to `OutputStream` of the `File` using `FileOutputStream` the [usual Java IO way](http://java.sun.com/docs/books/tutorial/essential/io/).
BalusC
Thank you so much BalusC! It works flawlessly now. I appreciate your effort and input!Thanks again!Regards, Peter
Peter
You're welcome.
BalusC
A: 

Bare Bones Browser Launch is a good solution. It's very easy to use:

BareBonesBrowserLaunch.openURL("http://www.stackoverflow.com");
Michael Angstadt
His intent is to browse to a HTML file bundled with the application. Besides, this isn't much better than the Java SE builtin `Desktop#browse()`. It's only useful if the client is still on the 5 yrs old Java 5 or earlier.
BalusC
Oh neato, I didn't even know that existed!
Michael Angstadt