簡體   English   中英

如何從Java代碼運行命令並讀取輸出?

[英]How can I run command from Java code and read the output?

我正在編寫代碼以執行命令並讀取輸出如果我在命令提示符下運行命令,則看起來像這樣 在此處輸入圖片說明

命令是

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

嘗試使用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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM