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.
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).
So what you're doing is this:
Parent
-> create child 1 -> change working directory of child 1
-> create child 2 -> invoke "ls"
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" );
(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
, 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
.