[英]How can I run command from Java code and read the output?
I am writing a code to execute a command and reading the output If I run the command on command prompt, it looks like this 我正在编写代码以执行命令并读取输出如果我在命令提示符下运行命令,则看起来像这样
Command is 命令是
echo 'excellent. awesome' | java -cp "*" -mx5g edu.stanford.nlp.sentiment.SentimentPipeline -stdin
Command produces multi line output. 命令产生多行输出。 How can I print this output in my java code? 如何在我的Java代码中打印此输出?
I have written following code, but it produces output as command itself that is 我已经编写了以下代码,但是它产生的输出本身就是命令
echo 'excellent. awesome' | java -cp "*" -mx5g edu.stanford.nlp.sentiment.SentimentPipeline -stdin
rather than actual command output as we can see it in the screenshot 而不是实际的命令输出,如我们在屏幕截图中所见
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();
}
Try using ProcessBuilder: 尝试使用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.