且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

尝试在java中执行命令时出错

更新时间:2022-12-07 17:40:51

所以,你遇到的问题似乎是你不明白为什么你在调用时会得到不同的结果程序以不同的方式。

So, it seems the problem you're having is that you don't understand why you get different results when you invoke the program in different ways.

以下是发生的事情: Runtime.geRuntime()。exec()创建一个新的进程,是父进程的子进程。每个进程都有自己的工作目录;当您分叉一个新进程时,它会继承父进程的工作目录。然后调用 cd 将更改当前进程的工作目录(这是一个内置的shell,但暂时忽略它,我稍后会介绍它。)

Here's what's going on: Runtime.geRuntime().exec() creates a new process, which is a child of the parent. Every process has its own working directory; when you fork a new process, it inherits the working directory of the parent. Invoking cd will then change the working directory of the current process (and this is a shell builtin, but ignore that for now and I'll get to it later).

所以你正在做的是:


Parent

- >创建子1 - >更改子1的工作目录

-> create child 1 -> change working directory of child 1

- >创建子2 - >调用ls

-> create child 2 -> invoke "ls"

请注意,子级2将继承其父级的工作目录。它不会知道子1的工作目录。所以取决于调用此方法的进程的工作目录(在您的情况下,终端或......我不知道,您的JDK安装? )你会得到不同的结果。

Note that child 2 will inherit the working directory of its parent. It won't know anything about the working directory of child 1. So depending on the working directory of the process that is invoking this method (in your case, either the terminal or...I don't know, your JDK install?) you will get different results.

如果你想每次都得到相同的结果,你可以这样做:

If you want the same results every time, you could do something like this:

Process p = Runtime.getRuntime().exec( "ls /Users/apple/Documents/Documents/workspace/UserTesting/src" );

如果您希望能够从任何地方执行您的程序,只需使用完整路径:

And if you want to be able to exec your program from anywhere, just use the full path:

Process p = Runtime.getRuntime().exec( "java /Users/apple/Documents/Documents/workspace/UserTesting/NewFile" );

(当然,假设您已使用 javac 在该目录中构建 NewFile.class ,并且您具有执行它的权限。)

(assuming, of course, that you have already used javac to build NewFile.class in that directory, and that you have the right permissions to execute it.)

Re: cd ,正如我之前提到的,这是一个内置在shell中的命令。以这种方式使用 exec 调用命令时,可能会失败。您可以使用 get 方法进程读取标准错误来检查。

Re: cd, as I mentioned before this is a command that's built into your shell. When you invoke the command using exec in this way, it is likely failing. You can check on that by reading standard error using the getErrorStream() method of Process.