简体   繁体   中英

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

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

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM