Java 爪哇语;tasklist.exe/fo csv/nh“;在进程waitFor中加载命令需要花费很长时间

Java 爪哇语;tasklist.exe/fo csv/nh“;在进程waitFor中加载命令需要花费很长时间,java,tasklist,Java,Tasklist,我在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);

我在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(),但我警告您,删除它可能会导致输出不完整/为空,因为它不会等待它返回输出。因此最好考虑等待或进程ISAcviv.()将输出附加到StrugBu建器并随后打印。