Reputation: 81
I am trying to create a Unix shell in Java. Everything works great expect for the "cd" change directory command. Anytime I try to change directories, it remains in the same directory.
I took a look at this with no luck.
Here is a snippet of the code that I am using.
try
{
Process p = null;
File directory = new File("/Users/myName");
if(inputList.get(0).equals("cd")
{
System.setProperty("user.dir", "Users/myName");
System.out.println(System.getProperty("user.dir"));
ProcessBuilder pb = new ProcessBuilder("cd");
pb.directory(directory);
System.out.println(pb.directory);
p = pb.start();
}
}
Note that when printing the getProperty command returns to me the correct directory address. Also note that when printing pb.directory(), it also prints out the correct directory address. However when executing the "pwd" command next, it shows that I am in the directory of my project.
Upvotes: 1
Views: 1942
Reputation: 15199
In Unix, the current working directory is a property of a specific process. Java doesn't provide any means of manipulating this by default (the "user.dir" property provides a similar but not identical feature, i.e. it is the location from which relative pathnames are resolved, but it does not actually control the Unix working directory). You can change the current directory of a subprocess - which is what you are doing with ProcessBuilder.directory() in the code you posted - but any such change will not be remembered after the subprocess terminates.
Executing a 'cd' command as you're trying to do is pointless -- the command will change its working directory, then immediately terminate, forgetting the change that has been made.
What you need to do, therefore, is track that directory in a variable and use it as the directory for every subsequent command you execute. In code, I'd be expecting to see something like this:
if(inputList.get(0).equals("cd")
{
File newDirectory = new File(inputList.get(1));
if (!newDirectory.exists() || !newDirectory.isDirectory())
/* handle error here */
....
else
/* otherwise change is successful */
directory = newDirectory
/* no need to actually start a process here */
}
// ...
else
{
ProcessBuilder pb = new ProcessBuilder(inputList.get(0));
pb.directory(directory);
// ....
p = pb.start();
}
Upvotes: 2