How to write and run terminal command to be execute in java program

158 Views Asked by At

  String str;
            Process p;
            try {
                String command = "wmctrl -l|awk '{$1=\"\"; $2=\"\"; $3=\"\"; print}'";
                p = Runtime.getRuntime().exec(command);
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(p.getInputStream()));
                while ((str = br.readLine()) != null) {

                        activeWindowtitles.add(str);
                        System.out.println(str);
                }
                p.waitFor();
                p.destroy();
            } catch (Exception ex) {
            }

I am writing a java code to get all applications name in Linux system. I found a command to achieve this. I ran this command in Terminal and it works fine. But it is not working in Java code as i want only applications name instead of other details. The command is "wmctrl -l | awk '{$1=""; $2=""; $3=""; print}'" I am getting full output after executing this in java code.

Please tell me how to write this command properly.. Thanks

1

There are 1 best solutions below

0
On

Personally I would put the wmctrl command in a script and do something like this:

public static List<String> getRunningApps(String executablePath) throws IOException, InterruptedException {
    final String ERR_LOG_PATH = "stderr.log";
    List<String> result = new ArrayList<>();
    ProcessBuilder pb = new ProcessBuilder(executablePath);
    pb.redirectError(new File(ERR_LOG_PATH));
    Process p = pb.start();
    int exitCode = p.waitFor();
    if (exitCode != 0) {
        throw new RuntimeException(String.format("Error get apps. Check error log %s%n", ERR_LOG_PATH));
    }
    try (Scanner s = new Scanner(p.getInputStream())) {
        while (s.hasNextLine()) {
            result.add(s.nextLine().trim());
        }
    }
    return result;
}

That way you can tweak it more easily and keep your code cleaner. The script I used was:

#!/bin/bash
wmctrl -l | awk '{$1=""; $2=""; $3=""; print}'