2015-04-02 143 views
0

我寫一個代碼執行命令和讀取輸出 如果我在命令提示符下運行命令,它看起來像這樣enter image description here如何從Java代碼運行命令並讀取輸出?

命令是

echo 'excellent. awesome' | java -cp "*" -mx5g edu.stanford.nlp.sentiment.SentimentPipeline -stdin

命令產生多行輸出。我怎樣才能打印這個輸出在我的java代碼?

我已經寫了下面的代碼,但它產生的輸出命令本身就是

echo 'excellent. awesome' | java -cp "*" -mx5g edu.stanford.nlp.sentiment.SentimentPipeline -stdin

,而不是實際的命令輸出,我們可以看到它的屏幕截圖

final String cmd = "java -cp \"*\" -mx5g edu.stanford.nlp.sentiment.SentimentPipeline -stdin"; 
    final String path = "C:/Project/stanford-corenlp-full-2015-01-29/stanford-corenlp-full-2015-01-29"; 

    String input = "excellent"; 
    String cmdString = "echo '" +input + "' | " + cmd; 
    Process process = Runtime.getRuntime().exec(cmdString,null, new File(path)); 
    process.waitFor(); 
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); 
    String line = reader.readLine(); 
    while (line != null) { 
     System.out.println(line); 
     line = reader.readLine(); 
    } 
+0

能否詳細說明 - *它產生輸出爲命令本身而不是實際的命令輸出*? – TheLostMind 2015-04-02 05:56:04

+0

我認爲你可能會犯錯。第一個參數只是命令名,另一個是包含命令參數的字符串數組。 – Clashsoft 2015-04-02 06:16:56

+0

您可以通過編程方式訪問'SentimentModel',這比單獨的流程中的管道要容易得多。 – 2015-04-02 16:07:18

回答

0

嘗試使用ProcessBuilder:

try { 
     ProcessBuilder pb = new ProcessBuilder("your command here"); 
     pb.redirectErrorStream(true); 
     Process p = pb.start(); 
     InputStream is = p.getInputStream(); 
     BufferedReader br = new BufferedReader(new InputStreamReader(is)); 
     while ((line = br.readLine()) != null) { 
       System.out.println(line); 
     } 
     p.waitFor(); 
} catch (InterruptedException e) { 
    //handle exception 
}