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

查看:22
本文介绍了如何使用“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.

当前工作目录很重要的一种情况是执行外部进程(使用ProcessBuilderRuntime.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).

注意:当前工作目录可以从 系统属性 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天全站免登陆