在OS X上使用Runtime.exec()打开应用程序

时间:2013-06-08 01:08:17

标签: java macos process runtime.exec

如何在OS X上使用Runtime.exec()打开应用程序?

我的导师确实给了我们一个如何做的例子,除了唯一的问题是他在使用Mac OS X时使用Windows,这是我到目前为止定制的代码:

public class Runtime_execution{
public static void main(String args[]){
    Runtime rt = Runtime.getRuntime();
    Process proc;
    try{
        if(System.getProperty("os.name").startsWith("Mac OS X")){
//                run an OS specific program
            proc = rt.exec("Contacts");
        }else{
            proc = rt.exec("gedit");
        }
        System.out.println("Before calling waitFor() method.");
        proc.waitFor(); //  try removing this line
        System.out.println("After calling waitFor() method.");
    }catch(Exception e){
        System.out.println("Contacts is an unknown command.");
    }
}
}
// find out what the os name is for Mac OS X
class Random{
public static void main(String args[]){
    System.out.println(System.getProperty("os.name"));
}
}

当我运行程序时,输出保持显示:

Contacts is an unknown command. 

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

在OSX中,您需要通过命令行运行可执行文件,这是Runtime.exec正在执行的操作。

试试这个:

rt.exec("/Applications/Contacts.app/Contents/MacOS/Contacts");

或者你可以做一个

rt.exec("open /Applications/Contacts.app");