0

For example, the current directory is D:\, then I want to run dir on C:\. Via this post I know && is useful to connect 2 commands: runtime.exec("cmd.exe /k c: && dir"). But how to make the process to wait some seconds before the 2nd command being executed,i.e. after switch to C:\ and before dir operation. In my real scenario I need to check the feedback of the 1st command.

And how to keep the cmd window unclosed after execution?

xin
  • 309
  • 2
  • 19
  • Why don't you just call `Runtime.exec()` a second time? You don't seem to need to pipe the output of the first command so you could just read the output stream of the first process and then execute another process. – Thomas Apr 10 '18 at 07:29
  • @Thomas I need the 1st command to set up environment for the 2nd command. If i call hem one by one, the former one has no effect on the later one. In this example, the 1st cmd change directory to C:\ but the 2nd cmd still output the files in D:\. They are independent. :( – xin Apr 10 '18 at 08:43
  • Well, in that case it might be easiest to just provide a shell/batch script and call that. No need to go through all the hassle coordinating it from Java when you actually don't want/need to do that. – Thomas Apr 11 '18 at 11:07

1 Answers1

0

This makes the code very environment specific but anyway in this case you can consider creating a batch file that handles your stuff. In a standard batch file the commands would be something like:

c:
TIMEOUT 10
dir

I guess you can do it with cmd like

runtime.exec("cmd.exe /k  c:  && TIMEOUT 10 && dir")

I would do that instead of messing with threads in java since you already depend on the OS. But if you want to do it with threads you should execute the commands one by one and call Thread.sleep() in between.

Veselin Davidov
  • 7,031
  • 1
  • 15
  • 23
  • In your case, can I check the feedback of the 1st command during TIMEOUT 10 is running? If not, it won't help. I also tried to execute commands one by one, but the 2nd one shows the files and dirctories in D:\\, instead of C:\\,i.e.,the 2 commands are independent. – xin Apr 10 '18 at 08:37