Explain Codes LogoExplain Codes Logo

How to make a copy of a file in Android?

java
file-handling
android-development
file-copying
Alex KataevbyAlex Kataev·Sep 5, 2024
TLDR

Copying a file in Android? Adventure awaits on API 26+, just harness the power of java.nio.file.Files and its trusty copy method:

Files.copy(Paths.get(srcPath), Paths.get(destPath), StandardCopyOption.REPLACE_EXISTING);

Stranded on pre-API 26 land? Fear not, with FileInputStream and FileOutputStream, you can replicate data bit by bit:

try (InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile)) { byte[] buf = new byte[1024]; int len; // "Holy Buffering Batman, it's a while loop!" while ((len = in.read(buf)) > 0) out.write(buf, 0, len); }

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:

// It's like a mini-cleanup crew for your I/O operations try (FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel destChannel = new FileOutputStream(dest).getChannel()) { srcChannel.transferTo(0, srcChannel.size(), destChannel); }

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:

long position = 0; long size = srcChannel.size(); // It's not an endless loop, it's a while of persistence! while (position < size) { position += srcChannel.transferTo(position, size - position, destChannel); }

Kotlin to the rescue

Kotlin's got your back with copyTo extension function - simple, clean, and plays nice with overwrite:

val srcFile = File(srcPath) val destFile = File(destPath) // No treasure chest metaphors here, straight to the point srcFile.copyTo(destFile, overwrite = true)

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:

Path copied = Files.copy(sourcePath, destPath);

Recursive copying of directories

Directory copying needs more work. Here's where recursion with Files.walkFileTree comes into play:

Files.walkFileTree(srcDir.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // File copying is serious business, no place for heebie-jeebies here return copy(file); } private FileVisitResult copy(Path file) throws IOException { Files.copy(file, targetDir.resolve(srcDir.relativize(file))); return FileVisitResult.CONTINUE; } });

Fail-safe error handling

Don’t forget a nice and cozy try-catch block for your file operations:

try { Files.copy(srcPath, destPath); } catch (IOException e) { // "Bummer! An exception! Let's handle it like a champ" }

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:

if (!srcFile.exists()) { // "Oopsie daisy, source file is a no-show!" }

References