Search code examples
javaterminalexecute

Java - Error while executing command


I am trying to execute a command in Terminal (on Ubuntu) and I can't seem to run the command cd, here is my code:

public static void executeCommand(String[] cmd) {
    Process process = null;

    System.out.print("Executing command \'");

    for (int i = 0; i < (cmd.length); i++) {

        if (i == (cmd.length - 1)) {
            System.out.print(cmd[i]);
        } else {
            System.out.print(cmd[i] + " ");
        }
    }

    System.out.print("\'...\n");

    try {
        process = Runtime.getRuntime().exec(cmd);
        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        BufferedReader err = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        String line;

        System.out.println("Output: ");
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }

        System.out.println("Error[s]: ");
        while ((line = err.readLine()) != null) {
            System.out.println(line);
        }

    } catch (Exception exc) {
        System.err.println("An error occurred while executing command! Error:\n" + exc);
    }
}

(Just in case) Here is how I call it: executeCommand(new String[]{ "cd", "ABC" });

Any suggestions? Thanks!


Solution

  • cd is not an executable or script but rather a builtin command of the shell. Therefore you need:

    executeCommand(new String[]{ "bash", "-c", "cd", "ABC" });
    

    Although this shouldn't produce any error, it won't produce any output either. If multiple commands are required after this, it would be advisable to place all comands in a script file and call that from your Java application. This will not only make the code easier to read but also a re-compile won't be necessary should the commands change.