62,615
社区成员
发帖
与我相关
我的任务
分享
package CSDNTest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ProcessHandler {
/**
* @author coldanimal; ProcessHandler windowns version.
*/
public static boolean findRunningProcess(String processName) {
String platform = System.getProperty("os.name");
if (platform.contains("Windows")) {
return findRunningWindowsProcess(processName);
} else if (platform.contains("Linux")) {
return findRunningLinuxProcess(processName);
} else {
throw new RuntimeException("Unknown platform " + platform);
}
}
private static boolean findRunningLinuxProcess(String processName) {
return false;
}
private static boolean findRunningWindowsProcess(String processName) {
BufferedReader bufferedReader = null;
Process proc = null;
try {
proc = Runtime.getRuntime().exec("tasklist /FI \"IMAGENAME eq " + processName + "\"");
bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
if (line.contains(processName)) {
return true;
}
}
return false;
} catch (Exception ex) {
ex.printStackTrace();
return false;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (Exception ex) {
}
}
if (proc != null) {
try {
proc.destroy();
} catch (Exception ex) {
}
}
}
}
public static boolean killRunningProcess(String processName){
String platform = System.getProperty("os.name");
if(platform.contains("Windows")){
return killRunningWindowsProcess(processName);
}else if(platform.contains("Linux")){
return false;
}
throw new RuntimeException("Unkown platform " + platform);
}
private static boolean killRunningWindowsProcess(String processName){
try {
Runtime.getRuntime().exec("taskkill /IM " + processName);
System.out.println("kill process successful");
System.out.println("Process " + processName + " was killed. Mission completed.");
return true;
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("kill process fail");
System.out.println("Misson failed.");
return false;
}
}
public static void main(String[] args) {
if(ProcessHandler.findRunningProcess("notepad.exe")){
ProcessHandler.killRunningProcess("notepad.exe");
}
}
}