Get the list of running processes in Java example


Introduction
             This tutorial explains you on how to get the list of processes that are currently running in your machine which may be a background or foreground application. Complete Program is available at the bottom for download. Before we get into the actual code we should we aware of a software that is pre-installed in your machine.
This program is from Microsoft which comes along with your operating system. This can be found at C:\windows\system32\tasklist.exe
             We can also get the running processes list by executing this executable file through command prompt as shown in the screenshot below,

Command Line Output

Now, lets see how to get this done through Java programming. Just convert the above command line execution to programmatic steps, then we are done !! Simple..

Step 1:
            java.lang.Runtime.exec(String command) method executes the specified string command in a separate process. So using this lets execute tasklist.exe in Java
Process p = Runtime.getRuntime().exec("tasklist.exe");

Step 2:
           The above line will output string which is to be read line by line using BufferedReader in java, until the output string becomes NULL.

BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null)
{
   System.out.println(line); 


Thats it !! Now run the program you should be able to see the exact output as seen in the command line. Screenshot below for your reference.
Hope this example helps you to better understand on how to get the running processes list in Java.

Program Output

Tasklist.java


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class TaskList {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        String line;
        Process p = Runtime.getRuntime().exec("tasklist.exe");
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while ((line = input.readLine()) != null) {
            System.out.println(line);
        }
        input.close();
    }

}





Reactions:

0 comments :

Post a Comment