java 如何使用java关闭外部应用程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12140685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to close a external application with java
提问by user947265
Possible Duplicate:
Knowing which java.exe process to kill on a windows machine
How to kill a process in Java, given a specific PID
可能的重复:
知道在 Windows 机器上要杀死哪个 java.exe 进程
如何在给定特定 PID 的情况下杀死 Java 中的进程
I am trying to find out how to close a particular external exe namely cwserv5.exe. I have succeeded in starting a new external exe and closing it .But not an existing process. Can you help? Below is what I was tinkering with but really lost to be honest
我试图找出如何关闭特定的外部 exe,即 cwserv5.exe。我已成功启动一个新的外部 exe 并关闭它。但不是现有进程。你能帮我吗?下面是我正在修补的内容,但说实话真的输了
package com.TestCase;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ReStartEXE {
static Process pr;
public static void open() {
//ProcessBuilder
try {
Runtime rt = Runtime.getRuntime();
//Process pr = rt.exec("cmd /c dir");
pr = rt.exec("C:\APPLEGREEN\webserv\cwserv5rost.exe");
Thread.sleep(10000);
//pr.wait(10000);
//pr.waitFor();
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
// String line=null;
/*while((line=input.readLine()) != null) {
System.out.println(line);
}*/
//int exitVal = pr.waitFor();
//pr.destroy();
// Process.kill(pr);
// Runtime.getRuntime().exec("taskkill /F /IM cwserv5rost.exe");
//System.out.println("Exited with error code "+exitVal);
} catch(Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
}
public static void Close() {
pr.destroy();
}
}
回答by eboix
You can do this by executing a process to close the process that you want to close.
您可以通过执行一个进程来关闭要关闭的进程来完成此操作。
In your comments I can see taskkill
, which means that you're probably using Windows.
在您的评论中,我可以看到taskkill
,这意味着您可能正在使用 Windows。
Runtime rt = Runtime.getRuntime();
rt.exec("taskkill /F /IM cwserv5.exe");
This will force the process with image name cwserv5.exe
to end.
这将强制cwserv5.exe
结束带有图像名称的进程。
If you don't want to force it to end, don't use the /f
tag.
如果您不想强制结束,请不要使用该/f
标签。
For more information on taskkill
, go to cmd
(command prompt) and type taskkill /?
.
有关 的更多信息taskkill
,请转到cmd
(命令提示符)并键入taskkill /?
。
回答by Ankur
try this,
试试这个,
Process proc = rt.exec("taskkill /F /IM cwserv5.exe");
BufferedReader input = new BufferedReader(new InputStreamReader(proc.getInputStream()));
while ((line = input.readLine()) != null){
//do something
}
input.close();
code = proc.exitValue();
if(code==0){
//success
}
else{
//failure
}