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

open an application during runtime in Mac OSX using netbeans

我想在 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);
    } 


}    

好的,这需要一点挖掘。 运行 .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();
            }
        }

    }

}