Forum Stats

  • 3,872,140 Users
  • 2,266,394 Discussions
  • 7,911,063 Comments

Discussions

Accessing the process list

843810
843810 Member Posts: 46,938
edited Mar 18, 2011 9:45AM in Java Desktop Applications
I want to get the list of processes running on the OS (Moreover the applications running), is there any way to do it in java?

Comments

  • 848469
    848469 Member Posts: 17
    hi,

    try this.

    package Process;

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.InputStreamReader;
    import java.util.*;

    public class VBSUtils {
    private VBSUtils() { }

    public static List<String> listRunningProcesses() {
    List<String> processList = new ArrayList<String>();
    try {

    File file = File.createTempFile("realhowto",".vbs");
    file.deleteOnExit();
    FileWriter fw = new java.io.FileWriter(file);

    String vbs = "Set WshShell = WScript.CreateObject(\"WScript.Shell\")\n"
    + "Set locator = CreateObject(\"WbemScripting.SWbemLocator\")\n"
    + "Set service = locator.ConnectServer()\n"
    + "Set processes = service.ExecQuery _\n"
    + " (\"select name from Win32_Process\")\n"
    + "For Each process in processes\n"
    + "wscript.echo process.Name \n"
    + "Next\n"
    + "Set WSHShell = Nothing\n";

    fw.write(vbs);
    fw.close();
    Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
    BufferedReader input =
    new BufferedReader
    (new InputStreamReader(p.getInputStream()));
    String line;
    while ((line = input.readLine()) != null) {
    processList.add(line);
    }
    input.close();
    }
    catch(Exception e){
    e.printStackTrace();
    }
    return processList;
    }

    public static void main(String[] args){
    List<String> processes = VBSUtils.listRunningProcesses();
    String result = "";

    Iterator<String> it = processes.iterator();
    int i = 0;
    while (it.hasNext()) {
    result += it.next() +",";
    i++;
    if (i==10) {
    result += "\n";
    i = 0;
    }
    }
    msgBox("Running processes : " + result);
    }

    public static void msgBox(String msg) {
    javax.swing.JOptionPane.showConfirmDialog((java.awt.Component)
    null, msg, "VBSUtils", javax.swing.JOptionPane.DEFAULT_OPTION);
    }
    }
  • PhHein
    PhHein Member, Moderator Posts: 7,254 Silver Trophy
    Welcome to the forum. Please don't post in threads that are long dead and don't hijack other threads. When you have a question, start your own topic. Feel free to provide a link to an old post that may be relevant to your problem.

    I'm locking this thread now.
    And use code tags when posting code.
This discussion has been closed.