I want to create a full cross-plateform console in Java.
The problem I have is when I use the cd
command, the path is reset. For example, if I do cd bin
, then cd ../
, I will execute the first one from the directory of my app and the second one exactly from the same directory.
If I want to go to a specific folder and execute a program I have to do something like that:
cd C:\mydir & cd bin & start.exe
What I want to do is to split this cmd in different parts:
cd C:\mydir
then cd bin
then start.exe
How can I do that? Is there a way to store the current cd
path and use it then?
Here is the code I use:
String[] cmd_exec = new String[] {"cmd", "/c", cmd};
Process child = Runtime.getRuntime().exec(cmd_exec);
BufferedReader in = new BufferedReader(new InputStreamReader(child.getInputStream()));
StringBuffer buffer = new StringBuffer();
buffer.append("> " + cmd + "\n");
String line;
while ((line = in.readLine()) != null)
{
buffer.append(line + "\n");
}
in.close();
child.destroy();
return buffer.toString();
It executes the command, then return the content of the console. (This is for windows for the moment).
If you do cd you don't want to execute it. You just want to check if the relative path exists and then change a
to that directory. So I would propose you split your commands up in three: cd, dir/ls and other stuff. cd changes the dir, as I mentioned, by using a File currentDir, dir should just get folders and files of currentDir and list them and then the rest you should just execute as you do know.
Remember you can split a command string by "".split("&"); this way you can do "cd C:\mydir & cd bin & start.exe".split("&"); => {"cd C:\mydir", "cd bin", "start.exe"} and then you can execute them in order.
Good luck.
If you want to run a command from a specific directory, use
ProcessBuilder
instead ofRuntime.exec
. You can set the working directory using thedirectory
method before you start the process. Don't try to use thecd
command - you're not running a shell, so it doesn't make sense.Thanks to Mads, I was able to do the trick:
Here is the code I used:
Then you can execute the command calling:
Don't forget to add this attribute in your class: