Java calls browser to open URL (supports Mac, UNIX, Linux, windows)

From , 5 Years ago, written in Java, viewed 139 times.
URL https://pastebin.vip/view/eefc9e10
  1. import java.lang.reflect.Method;
  2.  
  3. public class OpenUrl {
  4.  
  5.         public static void openURL(String url) {
  6.                 try {
  7.                         browse(url);
  8.                 } catch (Exception e) {
  9.                 }
  10.         }
  11.  
  12.         private static void browse(String url) throws Exception {
  13.                 // 获取操作系统的名字
  14.                 String osName = System.getProperty("os.name", "");
  15.                 if (osName.startsWith("Mac OS")) {
  16.                         // 苹果
  17.                         Class fileMgr = Class.forName("com.apple.eio.FileManager");
  18.                         Method openURL = fileMgr.getDeclaredMethod("openURL",
  19.                                         new Class[] { String.class });
  20.                         openURL.invoke(null, new Object[] { url });
  21.                 } else if (osName.startsWith("Windows")) {
  22.                         // windows
  23.                         Runtime.getRuntime().exec(
  24.                                         "rundll32 url.dll,FileProtocolHandler " + url);
  25.                 } else {
  26.                         // Unix or Linux
  27.                         String[] browsers = { "firefox", "opera", "konqueror", "epiphany",
  28.                                         "mozilla", "netscape" };
  29.                         String browser = null;
  30.                         for (int count = 0; count < browsers.length && browser == null; count++)
  31.                                 // 执行代码,在brower有值后跳出,
  32.                                 // 这里是如果进程创建成功了,==0是表示正常结束。
  33.                                 if (Runtime.getRuntime()
  34.                                                 .exec(new String[] { "which", browsers[count] })
  35.                                                 .waitFor() == 0)
  36.                                         browser = browsers[count];
  37.                         if (browser == null)
  38.                                 throw new Exception("Could not find web browser");
  39.                         else
  40.                                 // 这个值在上面已经成功的得到了一个进程。
  41.                                 Runtime.getRuntime().exec(new String[] { browser, url });
  42.                 }
  43.         }
  44. }

Reply to "Java calls browser to open URL (supports Mac, UNIX, Linux, windows)"

Here you can reply to the paste above

captcha

https://burned.cc - Burn After Reading Website