2016-03-22 58 views
0

我想在Mac运行时使用netbeans打开应用程序,我使用了下面的代码,但它引发异常。我使用这个代码的窗口与我在Mac中使用它的几个变化。任何人都可以告诉我正确的代码。使用netbeans在Mac OSX运行时在运行时打开应用程序

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

你可以使用'Desktop.edit'如果你想调用的“默认”的编辑器文件,请参阅[如何与桌面类集成](https://docs.oracle.com/javase/tutorial/uiswing/misc/desktop.html)以获取更多详细信息 – MadProgrammer

+0

假设我想打开任何其他应用程序不是默认的,那么这个类对我来说不会有帮助 –

+0

Mac应用程序只是一个特殊的“文件夹”,所以你不能“运行”它们,而是你需要查看应用程序包的Contents/MacOS目录),这可能更像'/ Applications/TextEdit.app/Contents/MacOS/TextEdit'。我也建议直接在'Process'上使用'ProcessBuilder' – MadProgrammer

回答

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(); 
      } 
     } 

    } 

} 
+0

我用你的代码打开了一个文件“hi.txt”,但它打印出下面的命令= /Application/TextEdit.app文件/users/apple/Documents/hi.txt不存在。用1 –

+0

退出这听起来很愚蠢,但尝试使用'new File(“/ users/apple/Documents/hi.txt”)。exists()'并确保当前用户存在并且可以访问它。 – MadProgrammer

+0

不能按预期工作 –

相关问题