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

标签 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);
    } 


}    

最佳答案

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

    }

}

关于java - 使用 netbeans 在 Mac OSX 中运行时打开应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36147226/

相关文章:

java - Ignite CacheStore 实现在服务器端抛出 ClassNotFoundException

java - 无法在 Play Frame 工作应用程序中导入 com.google.firebase.FirebaseApplication

java - Arraylist 发生奇怪的错误

objective-c - 在 Cocoa 应用程序中跟踪实际使用时间

objective-c - 使用未声明的标识符

java - 如何在 netbeans IDE 7.4 中指定构建选项

java - 从文件中读取文本时出现问题 - FileNotFoundException

java - 带 try/catch 的 while 循环会导致无限循环

javascript - 与 Sproutcore+Phonecap/Titanium 相比,使用 Cocoa 创建 iPhone、iPad 和 Mac 应用程序有何优势?

java - NetBeans 在导入的 jdde Pretty-tools jar 文件中找不到类