【发布时间】:2011-08-09 22:38:49
【问题描述】:
我想打开一个新的终端窗口,它会在打开时运行某个命令。它最好需要是一个真正的原生窗口,我不介意为 linux/osx/windows 编写不同的代码。
我假设模拟终端可以工作,只要它支持真实终端可以执行的所有操作,而不仅仅是打印命令的输出行。
【问题讨论】:
我想打开一个新的终端窗口,它会在打开时运行某个命令。它最好需要是一个真正的原生窗口,我不介意为 linux/osx/windows 编写不同的代码。
我假设模拟终端可以工作,只要它支持真实终端可以执行的所有操作,而不仅仅是打印命令的输出行。
【问题讨论】:
这行得通吗?
// windows only
Process p = Runtime.getRuntime().exec("cmd /c start cmd.exe");
p.waitFor();
【讨论】:
打开一个实际的终端窗口肯定需要为每个操作系统使用不同的代码。对于 Mac,您需要以下内容:
Runtime.getRuntime().exec("/usr/bin/open -a Terminal /path/to/the/executable");
【讨论】:
-a 说明您要用来打开文件的应用程序——在这种情况下它是终端。对于 Word 文档,它会是 -a Word /path/to/word/document.doc 你用带引号的空格包围应用程序。 -a "Sublime Text" path/to/code/file.js
我在 Ubuntu(X11 Desktop) 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 在终端中执行此选项的参数。【讨论】:
x-terminal-emulator 上测试过,无需路径前缀“/user/bin”即可直接工作,其他发行版是否也是如此?
您需要有关正在运行的操作系统的信息。为此,您可以使用如下代码:
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 所描述的不同调用
【讨论】:
要让 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 终端。
【讨论】: