打印所有 运行 个应用程序 Java

Printing all running applications Java

请原谅,这是我第一次提问。我正在寻找一种使用 Java 来打印我计算机上当前 运行 的所有应用程序的方法。

例如:

Google Chrome
Microsoft Word
Microsoft Outlook
Netbeans 8.0.2
Etc.

目前,我正在启动一个新进程,运行 命令 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) {

            for(int i = 0; i < line.length(); i++){

                try{
                if(line.substring(i, i + 13).equals(".app/Contents")){

                    //System.out.println(line.substring(i - 5, i + 3));
                    int j = 0;
                    String app = "";

                    while(!(line.charAt(i + j) == '/')){

                         app = app + line.charAt(i + j);

                        //System.out.print(line.charAt(i + j));
                        j--;

                    }

                    String reverse = new StringBuffer(app).reverse().toString();
                    System.out.println(reverse);
                    //System.out.println("");

                }/*System.out.println(line.substring(i, i + 13));*/}catch(Exception e){}

            }

            //System.out.println(line); //<-- Parse data here.
        }
    input.close();
    } catch (Exception err) {
        err.printStackTrace();
    }

那么,这是正确的方法吗?只是我需要使用一个不同的命令,还是总体上有更好的方法?

这几乎没有优化,但生成了一个看似合理的列表。排除 /System//Library/ 等下的任何内容的启发式方法似乎会产生良好的结果,但这取决于您。这真的取决于你想用这个列表做什么,它是否是你希望放在用户面前的东西。

package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Program {

    public static void main(String[] args) throws IOException {

        final Pattern APP_PATTERN = Pattern.compile("\/([^/]*)\.app\/Contents");

        Set<String> apps = new TreeSet<>();

        String line;
        Process p = Runtime.getRuntime().exec("ps -e");
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while (((line = input.readLine()) != null)) {
            if (!line.contains(" /System/") &&
                !line.contains("/Library/") &&
                !line.contains("/Application Support/")) {
                Matcher m = APP_PATTERN.matcher(line);
                if (m.find()) {
                    apps.add( m.group(1) );
                }
            }
        }
        System.out.println("Apps: " + apps);
        input.close();
    }
}