Page 1 of 1

Help with java.net.URL

Posted: 30 Aug 2007, 18:27
by general_koffi
Hey

Doing a JAVA project for school.

My problem:

I need to open an external document (.html in this case) from within a Java application. It needs to be opened with whatever is the default opener for that type of file on the machine the app is running on (so Internet Explorer for a .html on most Windows machines etc.)

The file is supposed to be opened when the user clicks a button, or menu option from within the Java app, so it uses the ActionListener etc

I can specify the file with java.net.URL easily enough, but I can't find a method to open the thing with its default program.

Any ideas?

Posted: 30 Aug 2007, 19:04
by hamin_aus

Code: Select all

public void launchBrowser(URL) 
{ 
    System.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + 
URL.toString()); 

}
:?:

Posted: 31 Aug 2007, 08:18
by rustypup
while jamin's solution will work in most cases, it's not really considered best practice.. the exec() function returns a java.lang.Process object which needs to have listeners installed to trap errors... along with this is the fact that, should the exec() command block pending input, the execution thread is blocked as well.

NOTE: the java.lang.Runtime instance is acquired by calling Runtime().getRuntime() and not System.getRuntime()...

java 6 onwards, (which is the flavour you should be developing in), has support for this built into the java.awt.Desktop class...

Code: Select all

java.awt.Desktop.getDesktop().browse(myURL.toURI());
if you're not developing in 1.6, consider using the JDIC, while at the same time you should really make a noise...

Re: Help with java.net.URL

Posted: 31 Aug 2007, 08:56
by Worship
Koffi I see you also need a little help.

This is what we figured out - This is the display webpage method
public static void displayURL (String url)
{
try
{
String cmd = null;
cmd = WIN_PATH + " " + WIN_FLAG + " " + url;
Process p = Runtime.getRuntime ().exec (cmd);
}
catch (IOException ex)
{
ex.printStackTrace ();
}
}
This is how to call the webpage
displayURL ("file:///G:/Comp/New%20Folder/index.htm");

Posted: 31 Aug 2007, 15:11
by general_koffi
if you're not developing in 1.6, consider using the JDIC, while at the same time you should really make a noise...
It's a bit late for that. We're in matric. :p

*Sigh*

Thanks, guys. Worship is in my computers class and needs to do exactly the same thing, so I'll be in touch with him.

Posted: 01 Sep 2007, 22:06
by Worship
Problem Solved :D