调用的guava lib: guava-13.0.1.jar
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
import com.google.common.base.Splitter;
public class KillProcess {
public static List
List
List
command.add("tasklist");
try {
ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream(true);
Process process = builder.start();
LineNumberReader ir = new LineNumberReader(
new InputStreamReader(process.getInputStream(), Charset.forName("gbk"))); //UTF8
String line;
while ((line = ir.readLine()) != null) {
if(!line.isEmpty()) {
ret.add(line);
}
}
if (process.isAlive()) {
process.waitFor();
}
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
public static void killProcess(String pid) {
List
command.add("taskkill");
command.add("/F");
command.add("/PID");
command.add(pid);
try {
ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream(true);
Process process = builder.start();
LineNumberReader ir = new LineNumberReader(
new InputStreamReader(process.getInputStream(), Charset.forName("gbk"))); //UTF8
String line;
StringBuffer sb = new StringBuffer();
while ((line = ir.readLine()) != null) {
sb.append(line);
}
String lines = sb.toString();
if (lines!=null && lines.contains("Error")) {
//String msg = String.format("%sn", lines);
//throw new Exception("结束进程失败:n" + msg);
}
if (process.isAlive()) {
process.waitFor();
}
} catch (Exception e) {
e.printStackTrace();
}
}
//对存在空格的进程名不好使,如"System Idle Process",但一般没问题
public static void killProcessWithName(String processName) {
List
for(String procInfo : processList) {
Iterator
.omitEmptyStrings().split(procInfo).iterator();
String procName = arr.next();
String pid = arr.next();
// System.out.println("procName: " + procName + " pid: " + pid);
if(procName.compareToIgnoreCase(processName)==0) {
killProcess(pid);
}
}
}
public static void killProcessWithName2(String processName) {
List
command.add("taskkill");
command.add("/f");
command.add("/im");
command.add(processName);
try {
ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream(true);
Process process = builder.start();
LineNumberReader ir = new LineNumberReader(
new InputStreamReader(process.getInputStream(), Charset.forName("gbk"))); //UTF8
String line;
StringBuffer sb = new StringBuffer();
while ((line = ir.readLine()) != null) {
sb.append(line);
}
String lines = sb.toString();
if (lines!=null && lines.contains("Error")) {
String msg = String.format("%sn", lines);
logger.error("结束进程失败:n" + msg);
}
if (process.isAlive()) {
process.waitFor();
}
} catch (Exception e) {
logger.error("结束进程失败 进程名:" + processName, e);
}
}
public static void main(String[] args) {
String procName = "winword.exe"; //匹配进程
KillProcess.killProcessWithName2(procName);
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)