出于某种原因,我在将输出发送到我用Java创建的进程时遇到了问题。外部进程在命令提示符下运行,特别的是我可以单击它,键入,按回车键,然后我将从程序中获得输出。另外我的程序可以读取来自程序的所有输出,它只是不能发送任何东西。
无论如何,这是我正在使用的相关代码,只是不起作用......
try {
ProcessBuilder builder=new ProcessBuilder(args);
builder.redirectErrorStream(true);
final Process p=builder.start();
// Process has been created and is running
try {
String b="";
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
final BufferedWriter output = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
new Thread(){public void run(){
// This thread will periodically send "get_time" to the process to get an update on its progress
while(true)
{
try {
Thread.sleep(1000);
p.exitValue();
// p.exitValue() only works when process has ended, so normal code goes in the catch block
output.close();
break;
// Leave the infinite loop if the program has closed
} catch (IOException ex) {
Logger.getLogger(OvMusicUI.class.getName()).log(Level.SEVERE, null, ex);
break;
// Leave the infinite loop if we tried closing our output stream, but it was already closed
} catch (InterruptedException ex) {
Logger.getLogger(OvMusicUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalThreadStateException e) {
try {
System.out.println("Outputted: get_time");
output.write("get_time" + System.lineSeparator());
output.flush();
// Give the process some input
} catch (IOException ex) {
Logger.getLogger(OvMusicUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}}.start();
while((b = input.readLine()) != null){
System.out.println(new Time(System.currentTimeMillis()).toString() + " " + b);
// Log all output the process gives
}
input.close();
} catch (IOException ex) {
Logger.getLogger(OvMusicUI.class.getName()).log(Level.SEVERE, null, ex);
}
// More code here
} catch (IOException ex) {
Logger.getLogger(OvMusicUI.class.getName()).log(Level.SEVERE, null, ex);
}
如果有必要,我可以给出一个示例命令和正在运行的外部程序的名称,以便您自己尝试...
谢谢!
编辑:以下是传递给ProcessBuilder的示例:Arrays.asList("VLC\vlc.exe", "-Irc", "-vvv", "http://www.youtube.com/watch?v=xfeys7Jfnx8", "--sout", "file/ogg:Untitled 1.ogg", "--play-and-exit", "--rc-quiet")
。唯一的区别是我使用绝对路径而不是相对路径。该计划是VLC Media Player 2.0.7。
答案 0 :(得分:2)
您的代码存在一些问题。首先,您通常应该不使用常规控制流的异常:它很昂贵,难以阅读,并且它使处理实际错误更加困难。产生调用Thread
的另一个p.waitFor()
通常会更好,并指示您的主要线程完成,例如使用wait
/ notify
。
此外,使用无限循环构建并使用break
而不是return
将使您的代码更难以调试;相反,请使用Timer
。
看起来外部程序的输出可能正常工作,但问题只是读取其输出。该程序可能正在缓冲其自己的输出,或者可能检测到它没有以交互方式运行并且表现不同。