我想打开一个新的终端窗口,在打开时运行某个命令。最好是一个真正的本地窗口,而且我不介意为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");
我曾在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 在终端内部执行这个选项的参数。
您需要了解有关正在运行的操作系统的信息。为此,您可以使用以下代码:
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 终端。
-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