We help IT Professionals succeed at work.

Alternative approach for file copying instead of Runtime.exec method

srikotesh asked
Hi Experts,

Runtime rt = Runtime.getRuntime();
Process p = rt.exec("cp " +sourceFile+" "+destFile);

Open in new window

is there any specic reason using the above code or it is legacy code.
can i use alternative approach as below or any better approach is there for file copying

Files.copy(source.toPath(), dest.toPath());

Open in new window

Watch Question

That's definitely a legacy approach.  It's really against the spirit of Java to be calling directly to the OS to do something very simple like file copying.

You are much better to use the Files.copy() method.

The one using the Runtime will only work on Linux (or more generally an OS that has a built in "cp" command that is on the path) and any errors from that method will be very hard to handle correctly.

So take it out and put in your new code.