Forum Moderators: bakedjake
I'm trying to execute Linux Shell command from java application and get a runtime error after executing the above line:
Exception in thread "main" java.io.IOException: Cannot run program "cd": java.io.IOException: error=2, No such file or directory
at java.lang.ProcessBuilder.start(ProcessBuilder.java:459)
at java.lang.Runtime.exec(Runtime.java:593)
at java.lang.Runtime.exec(Runtime.java:431)
at java.lang.Runtime.exec(Runtime.java:328)
at LauncherWin.main(LauncherWin.java:137)
Caused by: java.io.IOException: java.io.IOException: error=2, No such file or directory
at java.lang.UNIXProcess.<init>(UNIXProcess.java:148)
at java.lang.ProcessImpl.start(ProcessImpl.java:65)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:452)
... 4 more
It works for other commands like "pwd", "ls -l" etc. but not "cd".
Any idea why?
thanks in advance,
tatarin
You could try the exec method that accepts a working directory argument, [java.sun.com...]
Andrew
OK, you can run an instance of the shell of your choice and send it commands via the Process's OutputStream, this allows you to simulate typeing commands into the terminal. Here I've used bash with an initial working directory of /bin the program should print out "/bin" followed by "/" as the cd command moves to the parent directory.
File wd = new File("/bin");
System.out.println(wd);
Process proc = null;
try {
proc = Runtime.getRuntime().exec("/bin/bash", null, wd);
}
catch (IOException e) {
e.printStackTrace();
}
if (proc != null) {
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
out.println("cd ..");
out.println("pwd");
out.println("exit");
try {
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
proc.waitFor();
in.close();
out.close();
proc.destroy();
}
catch (Exception e) {
e.printStackTrace();
}
}
Andrew
[edited by: Little_G at 12:02 pm (utc) on Mar. 29, 2008]
when i run this script manually from command line it works fine. I know crontab starts in the root directory but the script you provided should have moved to the directory where i need to execute that cause it does work manually.
thanks,
tatarin