Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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 (46k 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.6k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 9, 2019 in Java by Nigam (4k points)
0 votes
1 answer
asked Sep 16, 2019 in Java by Anvi (10.2k points)

Browse Categories

...