本文主要是介绍java终止操作系统进程的demo,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
判断操作系统是否有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");}}}
这篇关于java终止操作系统进程的demo的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!