Java Source - Chương trình chỉ định kết thúc tiến trình của ứng trong windown(How to kill a Windows process using java?).



Hôm nay thấy một mã của một chương trình JAVA khá hay nên lưu lại trên blog, chương trình này cho phép kết thúc(end process) chỉ định một ứng dụng bất kỳ đang chạy trên Windows, giống với Windows Task Manager.






Dưới đây là source code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package processkill;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author NGOCSON
 */
public class ProcessKill {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            // TODO code application logic here
            String processName = "notepad++.exe";

            //System.out.print(isProcessRunging(processName));

            if (isProcessRunging(processName)) {

                killProcess(processName);
            }       
        } catch (Exception ex) {
            Logger.getLogger(ProcessKill.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static boolean isProcessRunging(String serviceName) throws Exception {

        Process p = Runtime.getRuntime().exec(TASKLIST);
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {

            System.out.println(line);
            if (line.contains(serviceName)) {
                return true;
            }
        }

        return false;

    }

    public static void killProcess(String serviceName) throws Exception {
        Runtime.getRuntime().exec(KILL + serviceName);
    }   
   
    private static final String TASKLIST = "tasklist";
    private static final String KILL = "taskkill /IM ";   
   
}


Sau khi chạy thì chương trình sẽ in ra một danh sách các tiến trình đang hoạt động trên Windows như hình bên dưới.










No comments:

Post a Comment