I try to use following command to execute a Windows command in a given directory.
try{
String command = "cmd /c start cmd.exe";
Process child = Runtime.getRuntime().exec(command);
OutputStream out = child.getOutputStream();
out.write("cd /d C:\\_private\\Files\\testfiles".getBytes());
out.flush();
out.write("for /f \"DELIMS=\" %x in ('dir /ad /b') do move \"%x*.*\" \"%x\\\"".getBytes());
out.close();
}catch(IOException e){
}
It just open up a Command prompt in directory, where Java project is located.
asked Jul 26, 2018 at 13:24
plaidshirt
5,81120 gold badges105 silver badges195 bronze badges
1 Answer 1
That process is already terminated. You only start cmd to start another cmd. That first cmd, to which you have a variable and to which you're writing is gone. Only the second one remains open.
Instead, start CMD only once and tell it to remain open:
String command = "cmd /k";
Next, please have a look on how to start programs with arguments.
Process process = new ProcessBuilder("cmd.exe", "/k").start();
answered Jul 26, 2018 at 13:32
Thomas Weller
61.2k23 gold badges144 silver badges264 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
plaidshirt
I tried this way too, but file is not created:
String[] cmd = {"\"cmd.exe\", \"/k\"", "cd /d C:\\_private\\Files\\myfiles", "copy NUL EMptyFile.txt"}; Process process = new ProcessBuilder(cmd).start();Thomas Weller
@plaidshirt That's not the right way. Just start
cmd /k and do the rest (i.e. cd and copy) via OutputStream outlang-java
execand use aProcessBuilderto create the process. Also break aString argintoString[] argsto account for things like paths containing space characters.