I am trying to write a unix terminal emulator in java. I am having a lot of trouble. It doesn’t seem like I can change the working directory of the program, so commands like “cd” aren’t working properly. My question is this, If I run a command that requires input from the user, is there any way to send that input to the running process?
Thanks so much, that was a lot of help. Here’s an example:
InputStream in = null;
OutputStream outS = null;
StringBuffer commandResult = new StringBuffer();
String line = null;
int readInt;
p = Runtime.getRuntime().exec("gksudo apt-get install firefox");
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();
This is the output:
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.
Why is it aborting before I can pipe in the “Y”?
Yes; see
Process#getOutputStream()to get the “standard input” (stdin) stream for aProcessobject.As for the issue of changing directory, I don’t believe the JVM can change its working directory once it has launched. However, your program could model the idea of the “current working directory” as a variable which it uses when it does things which are relative to that location (e.g. launching processes, listing directory contents, etc). The
ProcessBuilderclass even has a way to set the working directory for Processes it produces.