0

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();
}
2
  • You appear to be running youtube-dl directly, so this question has nothing to do with cmd.exe. The console window is not cmd. Commented Jun 23, 2017 at 15:21
  • There isn't anything you can easily do if you don't have access to the source code of youtube-dl and it uses full buffering when StandardOutput is a pipe. It will flush its buffer to the pipe either when its full (typically 4 KB) or at exit. The workarounds are complicated, such as DLL injection and API hooking or actively scraping a console screen buffer. Commented Jun 23, 2017 at 15:22

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.