在java代码中执行带有参数的外部程序
Process p;
String line;
String path;
String[] params = new String [3];
params[0] = "D:\\prog.exe";
params[1] = picA+".jpg";
params[2] = picB+".jpg";
try
{
p = Runtime.getRuntime().exec(params);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null)
System.out.println(line);
input.close();
}
catch (IOException e)
{
System.out.println(" procccess not read"+e);
}
我没有收到任何错误,只是什么都没有。在 cmd.exe prog.exe 中工作正常。
为了使这段代码正常工作,需要改进什么?
Process p;
String line;
String path;
String[] params = new String [3];
params[0] = "D:\\prog.exe";
params[1] = picA+".jpg";
params[2] = picB+".jpg";
try
{
p = Runtime.getRuntime().exec(params);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null)
System.out.println(line);
input.close();
}
catch (IOException e)
{
System.out.println(" procccess not read"+e);
}
I don't get any error, just nothing. In cmd.exe prog.exe is working fine.
What to improve in order to make this code working?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
p = new ProcessBuilder(params).start();
而不是p = Runtime.getRuntime().exec(params);
除此之外看起来不错。
Use a
p = new ProcessBuilder(params).start();
instead ofp = Runtime.getRuntime().exec(params);
Other than that looks fine.
也许您应该使用 waitFor() 来获取结果代码。这意味着标准输出的转储必须在另一个线程中完成:
Perhaps you should use waitFor() to obtain the result code. This means that the dump of the standard output must be done in another thread:
我刚刚在我的系统上尝试过:
效果很好。
您确定您使用的程序确实在控制台上打印了一些内容吗?我看到它接受 jpeg 作为输入,也许它写入文件,而不是标准输出。
I just tried this on my system:
and it worked fine.
Are you sure the program you're using actually prints something to the console? I see it takes jpegs as input, maybe it writes to a file, not stdout.
就像从进程的输入流中读取一样,您也可以像这样从错误流中读取:
Just like reading from the input stream of the process, you can also read from the error stream like this: