如何使用Java运行时使用"cd"命令?

Ant*_*met 49 java terminal cd runtime runtime.exec

我创建了一个独立的java应用程序,我正在尝试使用Ubuntu 10.04终端中的"cd"命令更改目录.我使用了以下代码.

String[] command = new String[]{"cd",path};
Process child = Runtime.getRuntime().exec(command, null);
Run Code Online (Sandbox Code Playgroud)

但上面的代码给出了以下错误

Exception in thread "main" java.io.IOException: Cannot run program "cd": java.io.IOException: error=2, No such file or directory
Run Code Online (Sandbox Code Playgroud)

谁能告诉我如何实施它?

Joa*_*uer 56

没有可执行的调用cd,因为它无法在单独的进程中实现.

问题是每个进程都有自己的当前工作目录,并且cd作为一个单独的进程实现只会更改进程的当前工作目录.

在Java程序中,您无法更改当前的工作目录,也不需要.只需使用绝对文件路径.

当前工作目录很重要的一种情况是执行外部进程(使用ProcessBuilderRuntime.exec()).在这些情况下,您可以明确指定用于新启动的进程的工作目录(分别ProcessBuilder.directory()三个参数Runtime.exec()).

注意:可以从系统属性中 读取当前工作目录user.dir.您可能会想要设置该系统属性.请注意,这样做会导致非常不一致,因为它并不意味着可写.


use*_*066 16

请参阅以下链接(这解释了如何操作):

http://alvinalexander.com/java/edu/pj/pj010016

即:

String[] cmd = { "/bin/sh", "-c", "cd /var; ls -l" };
Process p = Runtime.getRuntime().exec(cmd);
Run Code Online (Sandbox Code Playgroud)


dee*_*ani 12

您是否为java运行时探索了此exec命令,使用您想要"cd"的路径创建一个文件对象,然后将其作为exec方法的第三个参数输入.

public Process exec(String command,
                String[] envp,
                File dir)
         throws IOException
Run Code Online (Sandbox Code Playgroud)

在具有指定环境和工作目录的单独进程中执行指定的字符串命令.

这是一种方便的方法.调用exec(command,envp,dir)形式的行为与调用exec(cmdarray,envp,dir)完全相同,其中cmdarray是命令中所有标记的数组.

更确切地说,命令字符串使用由调用new StringTokenizer(命令)创建的StringTokenizer分解为标记,而不进一步修改字符类别.然后,由标记化器生成的标记以相同的顺序放置在新的字符串数组cmdarray中.

Parameters:
    command - a specified system command.
    envp - array of strings, each element of which has environment variable settings in the format name=value, or null if the subprocess should inherit the environment of the current process.
    dir - the working directory of the subprocess, or null if the subprocess should inherit the working directory of the current process. 
Returns:
    A new Process object for managing the subprocess 
Throws:
    SecurityException - If a security manager exists and its checkExec method doesn't allow creation of the subprocess 
    IOException - If an I/O error occurs 
    NullPointerException - If command is null, or one of the elements of envp is null 
    IllegalArgumentException - If command is empty
Run Code Online (Sandbox Code Playgroud)


小智 7

这个命令工作得很好

Runtime.getRuntime().exec(sh -c 'cd /path/to/dir && ProgToExecute)
Run Code Online (Sandbox Code Playgroud)