How to make a copy of a file in Android?
Copying a file in Android? Adventure awaits on API 26+, just harness the power of java.nio.file.Files
and its trusty copy
method:
Stranded on pre-API 26 land? Fear not, with FileInputStream and FileOutputStream, you can replicate data bit by bit:
Master your resources, prevent leaks
Autopilot closure of streams
To prevent Ghosts of Memory Leaks Past (API 19+) Java introduced automatic stream closure with try-with-resources:
This ensures your streams bid you farewell properly once their job is done.
Copy large files, don't break a sweat
Copying large files? Use FileChannel.transferTo
! But remember, it's a 2GB cap to keep things civil. You may want a loop or checking the return value for a more thorough transfer:
Kotlin to the rescue
Kotlin's got your back with copyTo
extension function - simple, clean, and plays nice with overwrite:
Pro tips and tricks for seamless file copying
Easy file clone for up-to-date Android
On Android API 26+, file duplication got another tool - the Files.copy()
. Efficient, minimalistic, and plays nice with the exception Catch'em All:
Recursive copying of directories
Directory copying needs more work. Here's where recursion with Files.walkFileTree
comes into play:
Fail-safe error handling
Don’t forget a nice and cozy try-catch block for your file operations:
And for pre-API 19 versions, do your cleanup in the finally block if not using try-with-resources.
Check before you act
Before any copy operation, ensure source and destination are not figments of imagination:
References
Was this article helpful?