Java - 执行命令时出错

时间:2013-04-28 02:27:27

标签: java terminal execute

我正在尝试在终端(在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" });

有什么建议吗?谢谢!

1 个答案:

答案 0 :(得分:3)

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

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

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