Java执行命令行程序
我在执行命令行工具时遇到一些问题。我想从 WinRAR 执行 UnRAR.exe。我这样做:
Process process = runtime.exec("\"" + unrarPath + "\"" + " x -kb -vp " + "\"" + fileName + "\"", null, f.getParentFile());
我的问题是压缩文件受密码保护。如果我在控制台中执行该命令,系统会要求我输入密码。如果我让 Java 执行它,程序就会结束并且永远不会等待用户输入(密码)。
我尝试写入进程输出流,但这不起作用。关于在“不同”环境中执行的命令行程序的行为,我需要了解什么吗?
编辑:也许我还不够清楚。我的问题是:是否可以使用 Java 与命令行程序交互?
I have a little problem with executing a command line tool. I want to execute UnRAR.exe from WinRAR. I do it like this:
Process process = runtime.exec("\"" + unrarPath + "\"" + " x -kb -vp " + "\"" + fileName + "\"", null, f.getParentFile());
My problem is that the compressed file is password protected. If I execute the command in my console I'm asked for a password. If I let Java execute it the program just ends and never waits for a user input (the password).
I tried to write to the process outputstream but that didn't work. Is there anything I need to know about the behavior of command line programs executed in "different" environments?
EDIT: Maybe I wasn't clear enough. My question is: Is it possible to interact with a command line program with Java?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对我有用。也许您没有编写换行符并刷新流?
http://ideone.com/OUGYv
+1回答你的问题,
java.lang.Process
就是我的问题正在寻找!Works for me. Perhaps you didn't write a newline and flush the stream?
http://ideone.com/OUGYv
+1 to your question,
java.lang.Process
was what I was looking for!运行进程并与之交互的方法很少。
java中有一个Process类。它允许获取子进程的所有 3 个流(由您的 java 应用程序调用的进程)。
java帮助中的流程类:链接
在这里您可以找到一些在java中执行进程的代码示例:链接
但是,在进程结束后,您将可以使用来自输出和错误流的数据(您的程序将通过 .exec() 方法在线“停止”,直到子进程结束)。
要与正在运行的进程交互,您必须使用另一个线程。
使用线程捕获进程输出
与另一个进程Java交互
There are few methods to run process and interact with it.
There is
Process
class in java. It allows to get all 3 streams of subprocess (process called by your java app).Process class in java help: link
Here you can find few examples of code, that executes process in java: link
However data from output and error streams will be available for you after process ends (your program will be "stopped" on line with .exec() method until subprocess ends).
To interact with running process you have to use another thread.
Using a thread to capture process output
Interacting with another process Java