[英]Open a new prompt/terminal window from Java
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.
它最好需要是一个真正的本机窗口,而且我不介意为 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.我假设模拟终端可以工作,只要它支持真正终端可以做的一切,而不仅仅是打印命令的输出行。
Will this work?这会起作用吗?
// windows only
Process p = Runtime.getRuntime().exec("cmd /c start cmd.exe");
p.waitFor();
Opening an actual terminal window will definitely require different code for each OS.打开一个实际的终端窗口肯定需要为每个操作系统提供不同的代码。 For Mac, you want something like:
对于 Mac,您需要类似的东西:
Runtime.getRuntime().exec("/usr/bin/open -a Terminal /path/to/the/executable");
I've used this on Ubuntu(X11 Desktop) 10.04 ~ 14.04, and other Debian distro's.我在 Ubuntu(X11 桌面)10.04 ~ 14.04 和其他 Debian 发行版上使用过它。 Works fine;
工作正常; although, you may consider using Java's ProcessBuilder .
不过,您可以考虑使用 Java 的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.
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然后对于每个操作系统,您将不得不使用 Bala R 和 Mike Baranczak 所描述的不同调用
for Java to use Windows taskkill, try this:为了让 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
you need to have the cmd terminal running before taskkill works.您需要在 taskkill 工作之前运行 cmd 终端。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.