0

我正在尝试在终端(在 Ubuntu 上)执行命令,但我似乎无法运行命令cd,这是我的代码:

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);
    }
}

(以防万一)这是我的称呼: executeCommand(new String[]{ "cd", "ABC" });

有什么建议么?谢谢!

4

1 回答 1

3

cd不是可执行文件或脚本,而是 shell 的内置命令。因此,您需要:

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

虽然这不应该产生任何错误,但它也不会产生任何输出。如果在此之后需要多个命令,建议将所有命令放在一个脚本文件中并从您的 Java 应用程序中调用它。这不仅会使代码更易于阅读,而且如果命令发生更改,也不需要重新编译。

于 2013-04-28T02:35:23.470 回答