Open a new prompt/terminal window from Java

时光毁灭记忆、已成空白 提交于 2019-12-17 05:11:56

问题


I want to open a new terminal window, which will run a certain command upon opening. It preferably needs to be a real native window, and I don't mind writing different code for linux/osx/windows.

I'm assuming an emulated terminal would work, as long as it supports everything a real terminal would do and isn't just printing lines of output from a command.


回答1:


Opening an actual terminal window will definitely require different code for each OS. For Mac, you want something like:

Runtime.getRuntime().exec("/usr/bin/open -a Terminal /path/to/the/executable");



回答2:


Will this work?

// windows only
Process p = Runtime.getRuntime().exec("cmd /c start cmd.exe");
p.waitFor();



回答3:


I've used this on Ubuntu(X11 Desktop) 10.04 ~ 14.04, and other Debian distro's. Works fine; although, you may consider using Java's ProcessBuilder.

     // GNU/Linux -- example

Runtime.getRuntime().exec("/usr/bin/x-terminal-emulator --disable-factory -e cat README.txt");

 //  --disable-factory    Do not register with the activation nameserver, do not re-use an active terminal
//    -e                  Execute the argument to this option inside the terminal.



回答4:


You need information about the OS you're running. For that you could use code like this:

public static void main(String[] args)
    {
        String nameOS = "os.name";        
        String versionOS = "os.version";        
        String architectureOS = "os.arch";
        System.out.println("\n    The information about OS");
        System.out.println("\nName of the OS: " + 
        System.getProperty(nameOS));
        System.out.println("Version of the OS: " + 
        System.getProperty(versionOS));
        System.out.println("Architecture of THe OS: " + 
        System.getProperty(architectureOS));
    }

Then for each OS you would have to use different invocations as described by Bala R and Mike Baranczak



来源:https://stackoverflow.com/questions/5738259/open-a-new-prompt-terminal-window-from-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!