views:

6052

answers:

3

Does any one know how do I get the current open windows or process of a local machine using Java?

What I'm trying to do is: list the current open task, windows or process open, like in Windows Taskmanager, but using a multi-platform approach - using only Java if it's possible.

Thanks!

A: 

The only way I can think of doing it is by invoking a command line application that does the job for you and then screenscraping the output (like Linux's ps and Window's tasklist).

Unfortunately, that'll mean you'll have to write some parsing routines to read the data from both.

Process proc = Runtime.getRuntime().exec ("tasklist.exe");
InputStream procOutput = proc.getInputStream ();
if (0 == proc.waitFor ()) {
    // TODO scan the procOutput for your data
}
jodonnell
Yep,I already thought about that too, but I tough it could be done with Java only.And I think I would be better to use "ps -aux" instead of top. Thanks for the quick answer!
ramayac
+5  A: 

This is another aproach to parse the the process list from the command "ps -e":

    try {
        String line;
        Process p = Runtime.getRuntime().exec("ps -e");
        BufferedReader input =
                new BufferedReader(new InputStreamReader(p.getInputStream()));
        while ((line = input.readLine()) != null) {
            System.out.println(line); //<-- Parse data here.
        }
        input.close();
    } catch (Exception err) {
        err.printStackTrace();
    }

If you are using Windows, then you sould change the line: "Process p = Runtime.getRun..." etc... (3rd line), for one that looks like this:

    Process p = Runtime.getRuntime().exec
        (System.getenv("windir") +"\\system32\\"+"tasklist.exe");

Hope the info helps!

ramayac
A: 

There is no platform-neutral way of doing this. In the 1.6 release of Java, a "Desktop" class was added the allows portable ways of browsing, editing, mailing, opening, and printing URI's. It is possible this class may someday be extended to support processes, but I doubt it.

If you are only curious in Java processes, you can use the java.lang.management api for getting thread/memory information on the JVM.

hazzen