Java“tasklist.exe/fo csv /nh”命令在等待过程中永远加载

Java " tasklist.exe /fo csv /nh"command taking forever to load in process waitFor

我在 main() 中通过命令调用方法命令(" 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() ,但我给你一个警告,删除它会导致 incomplete/empty 输出,因为它不等待它到 return 输出。所以最好考虑等待或 while process isActive() 将输出附加到 stringBuilder 并在之后打印它。