Search code examples
javaoutputinputstreamwindows-console

How to get live java output from console application


I run code attached below but it gives output only after the command has completed in the String response. I want the console window activated during the running of command and get output of the command.

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();
}

Solution

  • Please try using waitFor method until the response is flushed properly to the output stream

     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();
        }
    

    Ref:

    Get output of cmd command from java code