如何使用“cd”使用 Java 运行时的命令?

发布于 2024-10-15 23:45:16 字数 399 浏览 2 评论 0原文

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

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

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

Exception in thread "main" java.io.IOException: Cannot run program "cd": java.io.IOException: error=2, No such file or directory

有人能告诉我如何实现它吗?

I've created a standalone java application in which I'm trying to change the directory using the "cd" command in Ubuntu 10.04 terminal. I've used the following code.

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

But the above code gives the following error

Exception in thread "main" java.io.IOException: Cannot run program "cd": java.io.IOException: error=2, No such file or directory

Can anyone please tell me how to implement it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

苍风燃霜 2024-10-22 23:45:17

没有名为 cd 的可执行文件,因为它无法在单独的进程中实现。

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

在 Java 程序中,您无法更改当前的工作目录,而且您也不需要这样做。只需使用绝对文件路径即可。

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

注意:当前工作目录可以从 系统属性 user.dir。您可能想设置该系统属性。请注意,这样做会导致非常严重的不一致,因为它并不是可写的

There is no executable called cd, because it can't be implemented in a separate process.

The problem is that each process has its own current working directory and implementing cd as a separate process would only ever change that processes current working directory.

In a Java program you can't change your current working directory and you shouldn't need to. Simply use absolute file paths.

The one case where the current working directory matters is executing an external process (using ProcessBuilder or Runtime.exec()). In those cases you can specify the working directory to use for the newly started process explicitly (ProcessBuilder.directory() and the three-argument Runtime.exec() respectively).

Note: the current working directory can be read from the system property user.dir. You might feel tempted to set that system property. Note that doing so will lead to very bad inconsistencies, because it's not meant to be writable.

伏妖词 2024-10-22 23:45:17

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

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

即:

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

See the link below (this explains how to do it):

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

i.e. :

String[] cmd = { "/bin/sh", "-c", "cd /var; ls -l" };
Process p = Runtime.getRuntime().exec(cmd);
尛丟丟 2024-10-22 23:45:17

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

public Process exec(String command,
                String[] envp,
                File dir)
         throws IOException

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

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

更准确地说,使用通过调用 new StringTokenizer(command) 创建的 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

Have you explored this exec command for a java Runtime, Create a file object with the path you want to "cd" to and then input it as a third parameter for the exec method.

public Process exec(String command,
                String[] envp,
                File dir)
         throws IOException

Executes the specified string command in a separate process with the specified environment and working directory.

This is a convenience method. An invocation of the form exec(command, envp, dir) behaves in exactly the same way as the invocation exec(cmdarray, envp, dir), where cmdarray is an array of all the tokens in command.

More precisely, the command string is broken into tokens using a StringTokenizer created by the call new StringTokenizer(command) with no further modification of the character categories. The tokens produced by the tokenizer are then placed in the new string array cmdarray, in the same order.

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
无名指的心愿 2024-10-22 23:45:17

这个命令运行得很好

Runtime.getRuntime().exec(sh -c 'cd /path/to/dir && ProgToExecute)

This command works just fine

Runtime.getRuntime().exec(sh -c 'cd /path/to/dir && ProgToExecute)
今天小雨转甜 2024-10-22 23:45:17

使用进程构建器的方法之一,我们可以传递我们期望执行 cmd 的目录。请看下面的例子。另外,您可以使用 wait for 方法提及进程的超时。

ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", cmd).directory(new File(path));

        Process p = builder.start();

        p.waitFor(timeoutSec, TimeUnit.SECONDS);

在上面的代码中,您可以将路径[我们期望执行cmd的地方]的文件对象传递给ProcessBuilder的目录方法

Using one of the process builder's method we could pass the directory where we expect the cmd to be executed. Please see the below example. Also , you can mention the timeout for the process, using wait for method.

ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", cmd).directory(new File(path));

        Process p = builder.start();

        p.waitFor(timeoutSec, TimeUnit.SECONDS);

In the above code, you can pass the file object of the path[where we expect the cmd to be executed] to the directory method of ProcessBuilder

等数载,海棠开 2024-10-22 23:45:17

我的首选解决方案是传入 Runtime 进程将在其中运行的目录。我将创建一个如下所示的小方法: -

    public static String cmd(File dir, String command) {
        System.out.println("> " + command);   // better to use e.g. Slf4j
        System.out.println();        
        try {
            Process p = Runtime.getRuntime().exec(command, null, dir);
            String result = IOUtils.toString(p.getInputStream(), Charset.defaultCharset());
            String error = IOUtils.toString(p.getErrorStream(), Charset.defaultCharset());
            if (error != null && !error.isEmpty()) {  // throw exception if error stream
                throw new RuntimeException(error);
            }
            System.out.println(result);   // better to use e.g. Slf4j
            return result;                // return result for optional additional processing
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

请注意,这使用 Apache Commons IO 库 即添加到 pom.xml

   <dependency>
       <groupId>commons-io</groupId>
       <artifactId>commons-io</artifactId>
       <version>2.10.0</version>
   </dependency>

以使用 cmd method 例如

public static void main(String[] args) throws Exception {
    File dir = new File("/Users/bob/code/test-repo");
    cmd(dir, "git status");
    cmd(dir, "git pull");
}

这将输出如下内容:-

> git status

On branch main
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean

> git pull

Already up to date.

My preferred solution for this is to pass in the directory that the Runtime process will run in. I would create a little method like follows: -

    public static String cmd(File dir, String command) {
        System.out.println("> " + command);   // better to use e.g. Slf4j
        System.out.println();        
        try {
            Process p = Runtime.getRuntime().exec(command, null, dir);
            String result = IOUtils.toString(p.getInputStream(), Charset.defaultCharset());
            String error = IOUtils.toString(p.getErrorStream(), Charset.defaultCharset());
            if (error != null && !error.isEmpty()) {  // throw exception if error stream
                throw new RuntimeException(error);
            }
            System.out.println(result);   // better to use e.g. Slf4j
            return result;                // return result for optional additional processing
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

Note that this uses the Apache Commons IO library i.e. add to pom.xml

   <dependency>
       <groupId>commons-io</groupId>
       <artifactId>commons-io</artifactId>
       <version>2.10.0</version>
   </dependency>

To use the cmd method e.g.

public static void main(String[] args) throws Exception {
    File dir = new File("/Users/bob/code/test-repo");
    cmd(dir, "git status");
    cmd(dir, "git pull");
}

This will output something like this: -

> git status

On branch main
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean

> git pull

Already up to date.
素年丶 2024-10-22 23:45:17

尝试使用:

Runtime.getRuntime.exec("cmd /c cd path"); 

这有效

Runtime r = Runtime.getRuntime(); 
r.exec("cmd /c pdftk C:\\tmp\\trashhtml_to_pdf\\b.pdf C:\\tmp\\trashhtml_to_pdf\\a.pdf cat output C:\\tmp\\trashhtml_to_pdf\\d.pdf"); 

以下无效
虽然使用数组命令不起作用,但

String[] cmd = {"cmd /c pdftk C:\\tmp\\trashhtml_to_pdf\\b.pdf C:\\tmp\\trashhtml_to_pdf\\a.pdf cat output C:\\tmp\\trashhtml_to_pdf\\d.pdf"}; r.exec(cmd);

仅供参考,我正在使用实用程序来检查操作系统,上面的窗口是否适用于除 Windows 之外的其他窗口,删除 cmd/c

Try Use:

Runtime.getRuntime.exec("cmd /c cd path"); 

This worked

Runtime r = Runtime.getRuntime(); 
r.exec("cmd /c pdftk C:\\tmp\\trashhtml_to_pdf\\b.pdf C:\\tmp\\trashhtml_to_pdf\\a.pdf cat output C:\\tmp\\trashhtml_to_pdf\\d.pdf"); 

The below did not work
While using array command did NOT WORK

String[] cmd = {"cmd /c pdftk C:\\tmp\\trashhtml_to_pdf\\b.pdf C:\\tmp\\trashhtml_to_pdf\\a.pdf cat output C:\\tmp\\trashhtml_to_pdf\\d.pdf"}; r.exec(cmd);

FYI am using utility to check OS if its windows above will work for other than windows remove cmd and /c

一梦浮鱼 2024-10-22 23:45:17

我通过让Java应用程序执行位于同一目录中的sh脚本来解决这个问题,然后在sh脚本中执行“cd”。

我需要“cd”到特定目录,以便目标应用程序可以正常工作。

I had solved this by having the Java application execute a sh script which was in the same directory and then in the sh script had done the "cd".

It was required that I do a "cd" to a specific directory so the target application could work properly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文