从Java中打开一个新的提示/终端窗口

12

我想打开一个新的终端窗口,在打开时运行某个命令。最好是一个真正的本地窗口,而且我不介意为Linux、OSX和Windows编写不同的代码。

我假设一个模拟终端会起作用,只要它支持真实终端所能做的一切,而不仅仅是打印命令输出的行。

5个回答

16

这会有效吗?

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

14

打开一个真正的终端窗口需要针对每个操作系统编写不同的代码。对于 Mac,你需要类似以下的代码:

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

-a states the application you want to use to open a file – in this case it is terminal. For a word document it would be -a Word /path/to/word/document.doc You surround apps with spaces with quotations. -a "Sublime Text" path/to/code/file.js - 55 Cancri

6

我曾在Ubuntu(X11桌面) 10.04 ~ 14.04以及其他Debian发行版上使用过它,效果不错;但是你可能考虑使用Java的ProcessBuilder

     // GNU/Linux -- 示例
Runtime.getRuntime().exec("/usr/bin/x-terminal-emulator --disable-factory -e cat README.txt");
// --disable-factory 不要向激活名称服务器注册,也不要重复使用活动终端 // -e 在终端内部执行这个选项的参数。

--disable-factory 在我的 Peppermint Linux 7 上无法工作。 - Stefan Reich
1
x-terminal-emulator 是最好的,但它与另一个程序(我的当前框中的 mate-terminal)相关联。它可以是 gnome-terminal、xterm 等等... 注意:--disable-factory 很好用,但并不总是可用的。 - JimmyLandStudios
@JimmyLandStudios,正如您所提到的,它与另一个程序相关联,它在Ubuntu以外的Linux发行版上是否可用?此外,在Ubuntu 20.04 LTS上测试时,“x-terminal-emulator”可以直接使用,而无需路径前缀“/user/bin”,其他发行版也是如此吗? - Shreck Ye

4
你需要关于你正在运行的操作系统的信息。为此,你可以使用以下代码:

您需要了解有关正在运行的操作系统的信息。为此,您可以使用以下代码:

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

然后对于每个操作系统,您需要使用不同的调用方式,如Bala R和Mike Baranczak所描述的那样。


0

如果想在Java中使用Windows的taskkill命令,可以尝试以下方法:

    try {
      // start notepad before running this app
      Process p1 = Runtime.getRuntime().exec("cmd /c start cmd.exe"); // launch terminal first
      p1.waitFor();
      Process p2 = Runtime.getRuntime().exec( "taskkill /F /IM notepad.exe" );  // now send taskkill command
      p2.waitFor();
      Process p3 = Runtime.getRuntime().exec( "taskkill /F /IM cmd.exe" );  // finally, close terminal
      p3.waitFor();
    } catch (IOException ex) {
        System.out.println(ex);
    } catch (InterruptedException ex) {
        Logger.getLogger(RT2_JFrame.class.getName()).log(Level.SEVERE, null, ex);
    } // close try-catch-catch

在使用 taskkill 命令之前,您需要先打开 cmd 终端。


欢迎来到StackOverflow!除了提供的代码外,您能否简要解释一下它的作用?记得始终提供一些上下文。 - CFV

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接