如何使用“cd”使用Java运行时的命令? [英] How to use "cd" command using Java runtime?

查看:861
本文介绍了如何使用“cd”使用Java运行时的命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

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

问题是每个进程都有自己的当前工作目录并实现 cd 作为一个单独的进程只会改变那个处理当前工作目录。

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.

在Java程序中你不能更改当前的工作目录,您不应该这样做。只需使用绝对文件路径。

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

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

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).

注意:当前工作目录可以从系统属性<中读取/ a> user.dir 。您可能会想要设置该系统属性。请注意,这样做会导致非常糟糕的不一致,因为 意味着无法写入

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.

这篇关于如何使用“cd”使用Java运行时的命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆