I have the following class. It allows me to execute commands through java.
public class ExecuteShellCommand {
public String executeCommand(String command) {
for future reference: running bash commands after cd , in a subdirectory:
import java.io.BufferedReader;
import java.io.InputStreamReader;
/*
$ ( D=somewhere/else ; mkdir -p $D ; cd $D ; touch file1 file2 ; )
$ javac BashCdTest.java && java BashCdTest
.. stdout: -rw-r--r-- 1 ubuntu ubuntu 0 Dec 28 12:47 file1
.. stdout: -rw-r--r-- 1 ubuntu ubuntu 0 Dec 28 12:47 file2
.. stderr: /bin/ls: cannot access isnt_there: No such file or directory
.. exit code:2
*/
class BashCdTest
{
static void execCommand(String[] commandArr)
{
String line;
try
{
Process p = Runtime.getRuntime().exec(commandArr);
BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = stdoutReader.readLine()) != null) {
// process procs standard output here
System.out.println(" .. stdout: "+line);
}
BufferedReader stderrReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line = stderrReader.readLine()) != null) {
// process procs standard error here
System.err.println(" .. stderr: "+line);
}
int retValue = p.waitFor();
System.out.println(" .. exit code:"+Integer.toString(retValue));
}
catch(Exception e)
{ System.err.println(e.toString()); }
}
public static void main(String[] args)
{
String flist = "file1 file2 isnt_there";
String outputDir = "./somewhere/else";
String[] cmd = {
"/bin/bash", "-c",
"cd "+outputDir+" && /bin/ls -l "+flist+" && /bin/rm "+flist
};
execCommand(cmd);
}
}