使用netbeans在Mac OSX中运行时打开应用程序

时间:2016-03-22 06:03:51

标签: java macos netbeans runtime .app

我想在Mac中使用netbeans在运行时打开一个应用程序,我使用了以下代码,但它会抛出异常。我在Windows中使用此代码,在Mac中使用它时进行了少量更改。任何人都可以建议我正确的代码。

else
  {
    try {

        Runtime r = Runtime.getRuntime();

        p = Runtime.getRuntime().exec("/Applications/TextEdit.app /Users/apple/Documents/java files/scratch files/hi.rtf");


        A4 a4sObj = new A4(new String[]{jComboBox2.getSelectedItem().toString()});  


    } catch (IOException ex) {
        Logger.getLogger(serialportselection.class.getName()).log(Level.SEVERE, null, ex);
    } 


}    

1 个答案:

答案 0 :(得分:2)

好的,所以需要一点点挖掘。运行.app包的首选方法似乎是使用open命令。为了让应用程序打开文件,您必须使用-a参数,例如......

import java.io.IOException;
import java.io.InputStream;

public class Test {

    public static void main(String[] args) {
        String cmd = "/Applications/TextEdit.app";
        //String cmd = "/Applications/Sublime Text 2.app";
        String fileToEdit = "/Users/.../Documents/Test.txt";

        System.out.println("Cmd = " + cmd);
        ProcessBuilder pb = new ProcessBuilder("open", "-a", cmd, fileToEdit);
        pb.redirectErrorStream(true);
        try {
            Process p = pb.start();
            Thread t = new Thread(new InputStreamConsumer(p.getInputStream()));
            t.start();
            int exitCode = p.waitFor();
            t.join();
            System.out.println("Exited with " + exitCode);
        } catch (IOException | InterruptedException ex) {
            ex.printStackTrace();
        }
    }

    public static class InputStreamConsumer implements Runnable {

        private InputStream is;

        public InputStreamConsumer(InputStream is) {
            this.is = is;
        }

        @Override
        public void run() {
            int read = -1;
            try {
                while ((read = is.read()) != -1) {
                    System.out.print((char)read);
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }

}