如何从控制台应用程序获取实时 java 输出

How to get live java output from console application

我在下面附加了 运行 代码,但它仅在 字符串响应 中的命令完成后才提供输出。我希望控制台 window 在 运行 命令执行期间激活并获取命令输出。

String command = "src\youtube-dl"
                + " --max-downloads " + maxdown.getText()
                + " --retries " + noofretry.getText()
                + " --write-all-thumbnails" + sub.getText() 
                + " " + url.getText();

String response = "";
try {   
  Process p = Runtime.getRuntime().exec(command);
  InputStream in = p.getInputStream();
  ByteArrayOutputStream baos = new ByteArrayOutputStream();

  int c = -1;
  while((c = in.read()) != -1) {
    baos.write(c);
    System.out.flush();
    response = response + new String(baos.toByteArray());
    System.out.println(response);
  }         

} catch (Exception e) {
  e.printStackTrace();
}

请尝试使用 waitFor 方法,直到响应正确刷新到输出流

 Process p = null;
    try {
        p = p = r.exec(cmd2);
        p.getOutputStream().close(); // close stdin of child

        InputStream processStdOutput = p.getInputStream();
        Reader r = new InputStreamReader(processStdOutput);
        BufferedReader br = new BufferedReader(r);
        String line;
        while ((line = br.readLine()) != null) {
             //System.out.println(line); // the output is here
        }

        p.waitFor();
    }
    catch (InterruptedException e) {
            ... 
    }
    catch (IOException e){
            ...
    }
    finally{
        if (p != null)
            p.destroy();
    }

参考:

Get output of cmd command from java code