Original post the one that most people were answering
Here is the code I have already tried doing this with
String workingDirectory = "/home"; String command = "cd ../"; ProcessBuilder pb = new ProcessBuilder(new String[] { "cmd", "/c", command }); pb.directory(new File(workingDirectory)); pb.redirectErrorStream(true); Process process = pb.start(); // Some time later once the process has been closed workingDirectory = pb.directory().getAbsolutePath(); System.out.println("Path: " + workingDirectory);
This does not work, once it finishes it comes out with the same working directory.
Any help would be greatly appreciated, this would be a very useful think to know.
To be more specific, I am looking to find the working directory of a dynamically created process in Java, such as in the snippet above. This is important because such as the predefined command above, working directories can change sometimes, I would like to save any changes into memory for later use.
I found a way to do this, and it seems to work problem free
Here is how I am handling the incoming working directory
public int osType = 1; // This is for Windows (0 is for Linux)
public boolean isValidPath(String path) {
try {
Paths.get(new File(path).getAbsolutePath());
} catch (InvalidPathException | NullPointerException ex) {
return false;
}
return true;
}
public String tracePath(String path) {
try {
if (!path.contains("%%") && !isValidPath(path)) return null;
if (path.contains("%%")) path = path.substring(path.indexOf("%%"));
int lastIndex = -1;
char filesystemSlash = ' ';
if (osType == 0)
filesystemSlash = '/';
if (osType == 1)
filesystemSlash = '\\';
if (osType == 0)
path = path.substring(path.indexOf(filesystemSlash));
if (osType == 1)
path = path.substring(path.indexOf(filesystemSlash) - 2);
String tmp = path;
boolean broken = true;
while (!isValidPath(tmp)) {
int index = tmp.lastIndexOf(filesystemSlash);
if (lastIndex == index) {
broken = false;
break;
}
tmp = tmp.substring(0, index);
lastIndex = index;
}
if (broken && lastIndex != -1) {
tmp = path.substring(0, lastIndex);
}
return tmp;
} catch (StringIndexOutOfBoundsException ex) {
return null;
}
}
Here is the method of ignoring issues with the path (by not using it)
public boolean setDirectory(ProcessBuilder pb, String path) {
try {
pb.directory(new File(new File(path).getAbsolutePath()));
return true;
} catch (Exception ex) {
return false;
}
}
Now here is how I am starting the process for Windows or Linux
File file = null;
if (osType == 1) {
ProcessBuilder pb = new ProcessBuilder(new String[] { "cmd", "/c", command + " & echo %% & cd" });
pb.redirectErrorStream(true);
if (!workingDirectory.equals(""))
setDirectory(pb, workingDirectory);
process = pb.start();
} else if (osType == 0) {
file = new File("script.sh");
FileWriter writer = new FileWriter(file, false);
writer.append(command + " && echo %% && pwd");
writer.flush();
writer.close();
ProcessBuilder pb = new ProcessBuilder(new String[] { "bash", System.getProperty("user.dir") + "/script.sh" });
pb.redirectErrorStream(true);
if (!workingDirectory.equals(""))
setDirectory(pb, workingDirectory);
process = pb.start();
} else
return;
Finally here is the loop that manages the process and the working directory
while (process.isAlive() || process.getInputStream().available() > 0) {
byte[] returnBytes = new byte[1024];
process.getInputStream().read(returnBytes);
char[] arr = new String(returnBytes).trim().toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
char c = arr[i];
if (Character.isDefined(c))
sb.append(c);
}
String response = sb.toString();
if (!response.equals("")) {
String path = tracePath(response.trim().replace("\n", "").replace("\r", ""));
if (path != null && osType == 1) {
if (Paths.get(path).toFile().exists())
workingDirectory = path;
} else if (path != null && osType == 0) {
if (Paths.get(path).toFile().exists())
workingDirectory = path;
}
client.sendMessage(response + '\r' + '\n');
}
}
if (file != null) file.delete();
Here is the output from the command receiving website
Connecting..
Connected.
Success. You have been connected -> Speentie
bash -c pwd
/root/hardsceneServer/remoteServer
%%
/root/hardsceneServer/remoteServer
bash -c cd ..
%%
/root/hardsceneServer
bash -c pwd
/root/hardsceneServer
%%
/root/hardsceneServer
bash -c dir
ircServer nohup.out remoteServer start.sh start1.sh start2.sh
%%
/root/hardsceneServer
bash -c cd ircServer
%%
/root/hardsceneServer/ircServer
bash -c dir
HardScene.jar hardscene_banned.properties start.sh
hardscene.properties nohup.out
%%
/root/hardsceneServer/ircServer