What I want to do is: first go into some directory and start my server in the same directory for that I need to use cd directory path
but I read previous threads and I got that I can’t use cd command since it is basically a system call rather than a command like ls
.
My only aim is to go somehow in my desired directory chosen by Directorychooser
and start python -m SimpleHTTPServer
. I tried all possible answers like using sh -c and all other solutions provided to question like how do I use cd command in java. Is this possible without using cd.
I also have address chosen by directorychooser into string address . Also how do I execute any other command in that directory. I am not sure if Run.exec
or runtime.exec can still help here as it doesn't do CD I tried !
Previous answers questions doesn't explain well how to use processbuilder and other thing, Any help appreciated .
Tried these as well -
Runtime.getRuntime().exec(sh -c 'cd /path/to/dir && ProgToExecute
Yes It is possible , I was also stuck into the same problem and I couldn’t do cd
anywhere and this solution is how I solved it .You can achieve what you want to do with ProcessBuilder. (Runtime.exec() didn’t help me there as well , as suggested by previous answers on stackoverflow)
Here is how you can achieve it :
In code :
ProcessBuilder pbuild = new ProcessBuilder(“command”); //split into number of tokens like following example
In your case are 3 like this :
ProcessBuilder pbuild = new ProcessBuilder("python" , "-m", "SimpleHTTPServer");
Now set the path where the process is to be executed i.e. you are indirectly performing cd directory-path
here
pbuild.directory(new File(address));
(You said you have your path stored in address ,I am assuming, so)
Now start the process
Process proc = pbuild.start();
Done! Compile and run . Command will be executed with cd
.