0 votes
1 view
in Java by (3.4k points)

It has always bothered me that the only way to copy a file in Java involves opening streams, declaring a buffer, reading in one file, looping through it, and writing it out to the other steam. The web is littered with similar, yet still slightly different implementations of this type of solution.

Is there a better way that stays within the bounds of the Java language (meaning does not involve exec-ing OS-specific commands)? Perhaps in some reliable open-source utility package, that would at least obscure this underlying implementation and provide a one-line solution?

1 Answer

0 votes
by (46.1k points)

As toolkit states above, Apache Commons IO is the process to go, particularly FileUtils.copyFile(); it manages all the heavy lifting for you.

And as a postscript, remark that new versions of FileUtils (like the 2.0.1 release) have appended the use of NIO for copying files; NIO can significantly increase file-copying performance, in a large part because the NIO routines defer copying straight to the OS/filesystem rather than handle it by reading and writing bytes through the Java layer. So if you're viewing for performance, it might be worth examining that you are using a recent version of FileUtils.

Related questions

0 votes
2 answers
asked Aug 23, 2019 in Python by Sammy (47.8k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 9, 2019 in Java by Nigam (4.1k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...