Java“ tasklist.exe /fo csv /nh”命令永远加载进程waitFor

问题描述

我在 main() 中通过 command(" tasklist.exe /fo csv /nh") 调用方法命令;

这是我的代码片段:

String command(String command)throws Exception
    {long start=System.currentTimeMillis();
        System.out.println(" Entered command execution starting,executing : "+command);
        String output="";
        //A string for accumulating the output given by command executed
        System.out.println(" On line 1 ");
 Process powerShellProcess = Runtime.getRuntime().exec(command);

  System.out.println(" On line 2 ");
  //Executing our command by Process
 powerShellProcess.waitFor();
  System.out.println(" On line 3 ");
  //Waiting for it to complete 
  powerShellProcess.getoutputStream().close();
  System.out.println(" On line 4 ");
  //Closing Output Stream
  String line;
  //A string for each line accumulation of standard output in while loop
  BufferedReader stdout = new BufferedReader(new InputStreamReader(
    powerShellProcess.getInputStream()));
    //BufferedReader for getting standard output given by command .
  while ((line = stdout.readLine()) != null) {
output+=line+",";
//Adding line by line output to String output
  }
  stdout.close();
  //Closing BufferedReader stdout
  BufferedReader stderr = new BufferedReader(new InputStreamReader(
    powerShellProcess.getErrorStream()));
    //BufferedReader for getting standard error given by command ( if any ).
    stderror="";
      //A string for each line accumulation of standard error in while loop
  while ((line = stderr.readLine()) != null) {
      stderror+=line;
      //Adding line by line standard error to String stderror
  }
  stderr.close();
  //Closing BufferedReader stderr
  long end=System.currentTimeMillis();
  System.out.println(" Ending command execution starting in "+(end-start)+" milliseconds . ");
  System.out.println(" Error : ");
  System.out.println(stderror);
  System.out.println(" Output : ");
  System.out.println(output);
  return output;
  //Returning standard output by command 
    }

它卡在 waitFor() 中并且需要很长时间才能加载,我无法弄清楚。

代码输出如下: 在线 1 第 2 行

进一步的帮助将不胜感激。

解决方法

尝试删除 .waitFor() ,但我给你一个警告,删除它会导致不完整/空的输出,因为它不等待它返回 output 。所以最好考虑等待或 while process isActive() 将输出附加到 stringBuilder 并在之后打印它。