我在 Windows 7 上运行 jdk。我尝试在我的 java 应用程序中运行外部软件 (pocketsphinx_continous.exe)。该软件永久运行(pocketsphinx_continous.exe)并将一些输出打印到控制台,我喜欢通过我的java应用程序读取这些输出。
如果我使用命令行中的一些参数运行“pocketsphinx_continous.exe”,一切都会正常工作,并且我会看到软件的输出。终止该进程后,我尝试在我的 java 应用程序中运行它。但是java打印没有输出到控制台。
这是我的代码:
public void start(){
try {
Runtime rt = Runtime.getRuntime();
String[] commands = {"D:/cmusphinx/pocketsphinx/bin/Release/x64/pocketsphinx_continuous.exe", "-hmm", "d:/cmusphinx/pocketsphinx/model/en-us/en-us", "-lm", "d:/cmusphinx/pocketsphinx/model/en-us/en-us.lm.bin", "-dict", "d:/cmusphinx/pocketsphinx/model/en-us/cmudict-en-us.dict", "-samprate", "16000/8000/48000", "-inmic", "yes"};
Process proc = rt.exec(commands);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Java 只会打印“这是命令的标准输出:”,仅此而已。但它不会崩溃,它仍在运行,没有任何错误。在我看来,java 会等待执行的命令完成,直到打印任何内容。但该软件将永久运行并打印一些新的结果......
有什么想法吗?
致以诚挚的问候
迈克
最佳答案
我建议您执行以下操作:
Process p = null;
ProcessBuilder b = new ProcessBuilder("D:/cmusphinx/pocketsphinx/bin/Release/x64/pocketsphinx_continuous.exe -hmm d:/cmusphinx/pocketsphinx/model/en-us/en-us -lm d:/cmusphinx/pocketsphinx/model/en-us/en-us.lm.bin -dict d:/cmusphinx/pocketsphinx/model/en-us/cmudict-en-us.dict -samprate 16000/8000/48000 -inmic yes");
try {
p = b.start();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader output = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
try {
while ( (line = output.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
使用ProcessBuilder
,您不必分隔参数。只需将整个命令复制到 String
中即可。
关于java:解析执行命令的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36319241/