How to get a list of current open windows/process with Java?

后端 未结 14 1337
抹茶落季
抹茶落季 2020-11-22 05:20

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

14条回答
  •  盖世英雄少女心
    2020-11-22 05:55

    Finally, with Java 9+ it is possible with ProcessHandle:

    public static void main(String[] args) {
        ProcessHandle.allProcesses()
                .forEach(process -> System.out.println(processDetails(process)));
    }
    
    private static String processDetails(ProcessHandle process) {
        return String.format("%8d %8s %10s %26s %-40s",
                process.pid(),
                text(process.parent().map(ProcessHandle::pid)),
                text(process.info().user()),
                text(process.info().startInstant()),
                text(process.info().commandLine()));
    }
    
    private static String text(Optional optional) {
        return optional.map(Object::toString).orElse("-");
    }
    

    Output:

        1        -       root   2017-11-19T18:01:13.100Z /sbin/init
      ...
      639     1325   www-data   2018-12-04T06:35:58.680Z /usr/sbin/apache2 -k start
      ...
    23082    11054    huguesm   2018-12-04T10:24:22.100Z /.../java ProcessListDemo
    

提交回复
热议问题