2017-06-23 38 views
0

現場的Java輸出I運行代碼附在下面,但它給輸出的命令已經在字符串響應完成之後。我希望在運行命令期間激活控制檯窗口並獲取命令的輸出。如何從控制檯應用程序

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

你似乎是運行'YouTube的-dl'直接,所以這個問題與cmd.exe無關。控制檯窗口不是cmd。 – eryksun

+0

有沒有什麼,如果你不能夠訪問YouTube的' - dl'的源代碼,你可以很容易做到,它採用全緩衝的時候'StandardOutput'是一個管道。它將在其完整(通常爲4 KB)或退出時將其緩衝區刷新到管道。解決方法很複雜,例如DLL注入和API掛鉤或主動刮取控制檯屏幕緩衝區。 – eryksun

+0

感謝致謝@eryksun –

回答

0

到響應

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

參考正確刷新到輸出流,請嘗試使用WAITFOR方法:

Get output of cmd command from java code

+0

謝謝@Pradeep –

相關問題