0

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.

plaidshirt
  • 5,189
  • 19
  • 91
  • 181
  • 2
    Possible duplicate of [Java Programming: call an exe from Java and passing parameters](https://stackoverflow.com/questions/5604698/java-programming-call-an-exe-from-java-and-passing-parameters) and [https://stackoverflow.com/questions/6434009/java-runtime-getruntime-exec-cmd-with-long-parameters](https://stackoverflow.com/questions/6434009/java-runtime-getruntime-exec-cmd-with-long-parameters) – jhamon Jul 26 '18 at 13:29
  • 1
    See also [When Runtime.exec() won't](http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html) for many good tips on creating and handling a process correctly. Then ignore it refers to `exec` and use a `ProcessBuilder` to create the process. Also break a `String arg` into `String[] args` to account for things like paths containing space characters. – Andrew Thompson Jul 26 '18 at 23:30

1 Answers1

3

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();
Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
  • 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();` – plaidshirt Jul 27 '18 at 06:57
  • @plaidshirt That's not the right way. Just start `cmd /k` and do the rest (i.e. `cd` and `copy`) via `OutputStream out` – Thomas Weller Jul 27 '18 at 08:37