2013-04-28 84 views
0

我想执行的终端(在Ubuntu)的命令,似乎我无法运行该命令cd,这里是我的代码:的Java - 错误而执行命令

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

有什么建议吗?谢谢!

+0

你想达到什么目的?你不能改变java的默认文件夹。它不是vb6 ...你可以通过更多的编码获得相同的效果。为此需要告诉我们在此之后你想要做什么 – tgkprog 2013-04-28 02:40:18

回答

3

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

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

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

+0

谢谢,这真的有帮助! – 0101011 2013-04-28 14:28:21