我正在尝试在终端(在 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" });
有什么建议么?谢谢!