场景是我手动启动命令提示符。然后我需要使用 Java 自动关闭命令提示符。如何使用 java 关闭命令提示符。任何人都可以帮助我
5 回答
Use the following code:
class CmdKill
{
public static void main(String args[])
{
try {
Runtime.getRuntime().exec("taskkill /f /im cmd.exe") ;
} catch (Exception e) {
e.printStackTrace();
}
}
}
Surely would help!!
Edit:
To kill a particular process, if u have the PID(from task manager.) you can use taskkill with /pid option.Refer for options here.But anyways you wont have the pid without looking into the task manager.The only solution seems as suggested by this SO answer that you start the process and get hold of the reference.
Since command prompt is a separate platform specific program you do not have any cross platform solution for this. You can however execute command exit
via Runtime.getRuntime().exec()
or process builder. It will hopefully work.
Fortunately this command has the same syntax on both windows and unix.
The question is whether you want to close command prompt while your program is still running or when program is terminated.
I think that in both cases better solution is to run your java program using platform specific script (e.g. bat file for windows and shell script for unix) that is responsible on closing the prompt.
If you want to run your program (that for example creates window) and close the prompt while the program is still running you can use javaw
instead of java
on windows.
对于这种情况,您可以像这样执行命令
Runtime.getRuntime().exec("command.exe /C" + "Your command");
这将打开命令提示符执行命令然后关闭它。希望这会奏效
这是我是怎么做到的
1)创建一个包含以下内容的批处理文件 java -Xms512M -Xmx512M -jar yourFileName.jar -o true EXIT
2) 使用你的退出输入流添加 System.exit(1);
这很简单。你只需要使用exit命令。此处提供了完整的解决方案