我正在编写一个代码来执行命令并读取输出 如果我在命令提示符下运行该命令,它看起来像
命令是
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 :(得分: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
}