Can someone please explain to me why I get a different output when I run the same command from Java

42 views Asked by At

When I run the command "pmset -g batt | egrep '([0-9]+\%).*' -o --colour=auto | cut -f1 -d';' " in the OSX terminal, it outputs the battery percentage (Eg. 55%).

But when I run the same command in my Java code, I get "Currently drawing from 'Battery Power'"

Here's how it looks in my Java code:

String cmd = "pmset -g batt | egrep '([0-9]+\\%).*' -o --colour=auto | cut -f1 -d';'";
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd);
BufferedReader stdOutput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));    
String output = stdOutput.readLine();
System.out.println(output);

I thought it had to do with the double backslash I'm using, but I checked and I don't think that's the reason.

Thanks

1

There are 1 answers

0
Elliott Frisch On

I think you need to read more from your Process, and you should use a ProcessBuilder.

for (;;) {
  String output = stdOutput.readLine();
  if (output == null) {
    break;
  }
  System.out.println(output);
}