判断操作系统是否有javaw.exe进程,如有,则杀死此进程
/**
*
*/
package cn.edu.zzuli.huang;
/**
* @author moon
*
*/
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("javaw.exe")){
ProcessHandler.killRunningProcess("javaw.exe");
}
}
}