Vishal Mali
Vishal Mali

Reputation: 11

File copy using getRuntime().exec()

I am trying to copy a file. Here is the source. Note, des is string variable containing the URL.

Process process = Runtime.getRuntime().
    exec("cmd.exe\t/c\tcopy\t"+source+"\t"+des);

Can anyone tell me why it does not work?

Upvotes: 1

Views: 4673

Answers (4)

Andrew Thompson
Andrew Thompson

Reputation: 168835

Advice:

  1. Use ProcessBuilder to construct the Process.
  2. That automatically takes care of '2' - break the command into parts.
  3. Merge the output streams (not entirely necessary, but makes it simpler to ..).
  4. Consume (and display) the output streams.
  5. But in general, read and implement all the recommendations of When Runtime.exec() won't.

Upvotes: 2

RanRag
RanRag

Reputation: 49577

I think you should use FileUtils.copyFile() but anyways try this.

String[] command = new String[5];
command[0] = "cmd";
command[1] = "/c";
command[2] = "copy";
command[3] = "test.java";
command[4] = "D:";
Process p = Runtime.getRuntime().exec (command);

Instead of passing your command as a single string construct an array and than pass it to exec.

I tried this

String command = "cmd /c copy test.java D:";

worked fine for me.

Upvotes: 4

yegor256
yegor256

Reputation: 105133

Why not just use FileUtils.copyFile()?

Upvotes: 1

Charlie Martin
Charlie Martin

Reputation: 112376

Runtime.exec, I believe, send the string to the command processor cmd.exe. So this is running cmd.exe, running another cmd.exe inside it, and passing your arguments. I don't have a Windows machine to test it on (thank Gods) but I think there are arguments to cmd.exe to tell it to run the arguments as a command line.

Upvotes: 1

Related Questions