请原谅,这是我第一次提问。我正在寻找一种使用 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();
}
}
关于java - 打印所有正在运行的应用程序 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35784250/