2016-03-03 108 views
2

请原谅,这是我第一次提出问题。我正在寻找使用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(); 
    } 

所以,这是正确的做法,是那里只是一个不同的命令,我需要使用或是否有更好的方法的整体?

+1

http://stackoverflow.com/questions/54686/how-to-get-a-list-of-current-open-windows-process-with-java类似于你在做什么 –

+0

这就是我开始了,但这只会给我所有的流程。我尝试使用.app/Contents解析所有内容,但这不起作用。 – dsiegler19

回答

0

这是很难优化,但产生一个貌似合理的清单。排除/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(); 
    } 
} 
+0

它适用于我的用途,但出于好奇,有没有什么办法可以告诉哪些应用程序在码头上运行(即不是背景助手应用程序)。 – dsiegler19

+0

我在编写代码时尝试着解决这个问题,但不认为它可能来自Java,因此也是启发式的。也许有Darwin API调用或.plist列出Dock内容?不太可能是一门精确的科学,但如果我找到更好的东西,我会编辑答案。 –

相关问题