天天看點

用Java打開一個網頁

很簡單:

/////////////////////////////////////////////////////////

//Bare Bones Browser Launch //

//Version 1.5 (December 10, 2005) //

//By Dem Pilafian //

//支援: Mac OS X, GNU/Linux, Unix, Windows XP//

//可免費使用 //

/**

* @author Dem Pilafian

* @author John Kristian

*/

import java.io.IOException;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

import javax.swing.JOptionPane;

public class BareBonesBrowserLaunch {

public static void openURL(String url) {

try {

browse(url);

} catch (Exception e) {

}

private static void browse(String url) throws Exception {

//擷取作業系統的名字

String osName = System.getProperty("os.name", "");

if (osName.startsWith("Mac OS")) {

//蘋果的打開方式

Class fileMgr = Class.forName("com.apple.eio.FileManager");

Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] { String.class });

openURL.invoke(null, new Object[] { url });

} else if (osName.startsWith("Windows")) {

//windows的打開方式。

Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);

} else {

// Unix or Linux的打開方式

String[] browsers = { "firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape" };

String browser = null;

for (int count = 0; count < browsers.length && browser == null; count++)

//執行代碼,在brower有值後跳出,

//這裡是如果程序建立成功了,==0是表示正常結束。

if (Runtime.getRuntime().exec(new String[] { "which", browsers[count] }).waitFor() == 0)

browser = browsers[count];

if (browser == null)

throw new Exception("Could not find web browser");

else

//這個值在上面已經成功的得到了一個程序。

Runtime.getRuntime().exec(new String[] { browser, url });