1

I am trying to create a CPU usage meter by executing a batch file and returning the result. Here is the method that gets the CPU usage. When the batch file is ran it returns the results in a wierd format so I sort through it looking for the only number which is the CPU usage percentage. The problem I am running into is that I cant return the number after I convert it from a string and try to store it in a variable. Here is the code:

public int getCPUload (){
String s = "";
int r = 0;
try {
    Process ps = Runtime.getRuntime().exec("Pc.bat");
    BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
    while((s = br.readLine()) != null) {
       if(s.matches(".*\\d+.*")){
          r = Integer.parseInt(s);
       } 
    }

}
catch( Exception ex ) {
    System.out.println("ERR: "+ex.toString());
}
    return r;
}

and here is the batch file "PC.bat":

wmic cpu get loadpercentage

Ultimately I would like to be able to loop this code to constantly update the value but im not sure how that can be done yet(on a seperate thread maybe?). Help and andvice would be appreciated

Zenith
  • 209
  • 3
  • 13

1 Answers1

2

use for to parse the Output of a command:

for /f "tokens=2 delims==" %%i in ('wmic cpu get loadpercentage /value') do set /a cpu=%%i
echo %cpu%

set /a gets rid of the "strange" line ending of wmic (obviously works only for numbers - perfect for this case)

Stephan
  • 53,940
  • 10
  • 58
  • 91