我无法与使用getOutputStream的进程进行交互。这里是我的代码:ProcessBuilder getOutputStream并与进程进行交互
Process p = null;
ProcessBuilder pb = new ProcessBuilder("/home/eric/this.sh");
pb.directory(new File("/home/eric/"));
p = pb.start();
InputStream in = null;
OutputStream outS = null;
StringBuffer commandResult = new StringBuffer();
String line = null;
int readInt;
int returnVal = p.waitFor();
in = p.getInputStream();
while ((readInt = in.read()) != -1)
commandResult.append((char)readInt);
outS = (BufferedOutputStream) p.getOutputStream();
outS.write("Y".getBytes());
outS.close();
System.out.println(commandResult.toString());
in.close();
这里是输出:
Reading package lists...
Building dependency tree...
Reading state information...
The following packages were automatically installed and are no longer required:
libmono2.0-cil libmono-data-tds2.0-cil libmono-system-data2.0-cil
libdbus-glib1.0-cil librsvg2-2.18-cil libvncserver0 libsqlite0
libmono-messaging2.0-cil libmono-system-messaging2.0-cil
libmono-system-data-linq2.0-cil libmono-sqlite2.0-cil
libmono-system-web2.0-cil libwnck2.20-cil libgnome-keyring1.0-cil
libdbus1.0-cil libmono-wcf3.0-cil libgdiplus libgnomedesktop2.20-cil
Use 'apt-get autoremove' to remove them.
The following extra packages will be installed:
firefox-globalmenu
Suggested packages:
firefox-gnome-support firefox-kde-support latex-xft-fonts
The following NEW packages will be installed:
firefox firefox-globalmenu
0 upgraded, 2 newly installed, 0 to remove and 5 not upgraded.
Need to get 15.2 MB of archives.
After this operation, 30.6 MB of additional disk space will be used.
Do you want to continue [Y/n]? Abort
this.sh只需运行 “gksudo apt-get的安装Firefox”
我不知道为什么它被中止并没有把我的输入“Y”谢谢。
我真的不认为你应该尽快关闭流,只要你发送了“Y”。 –
我可以将其移至最后,但不会改变行为。事情是在它到达我的outputStream之前它正在中止。 – Eric
第一次阅读时漏掉了一些东西。在获取输入和输出流之前,先从p.waitFor()开始。根据javadoc,这个等待直到过程死亡。这是你想要的吗?死后发送'Y'似乎毫无意义。 –