在java中运行内部和外部unix命令之间的区别

在java中运行内部和外部unix命令之间的区别

问题描述:

为什么内部unix命令(cd,pwd等)不能像使用Runtime.getRuntime()。exec()的外部命令(chmod,chown等)直接在java中运行?

Why can't internal unix commands (cd, pwd, etc) be run directly in java like external commands (chmod, chown, etc) using Runtime.getRuntime().exec() ?

请帮忙解释。

因为它们内置于shell中,而不是程序

Because they are built into the shell, rather than being programs in and of themselves.

最简单的方法是调用shell并使用-c选项传递命令:

The simplest thing to do is to invoke the shell and pass the command in using the -c option:

> bash -c pwd
/home/foo/bar/baz

...或者Java:

... or in Java:

Runtime.getRuntime().exec("bash -c pwd")

...或更一般地说:

... or more generally:

Runtime.getRuntime().exec(new String[]{"bash", "-c", command});

我们需要使用String []变体,否则,我们的命令会被StringTokenizer破坏它包含任何空格。

We need to use the String[] variant, otherwise, our command will get mangled by the StringTokenizer if it contains any whitespace.