How to Efficiently Copy Files in Java without Manual Looping
Java's traditional file copying approach using stream handling and manual looping can be cumbersome. However, there are more concise alternatives within the language, particularly in the newer NIO (New Input/Output) package.
NIO introduces the transferTo() and transferFrom() methods in the FileChannel class. These methods provide a direct and efficient way to transfer data between files.
NIO-Based File Copying Code
import java.io.File; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.StandardOpenOption; public class FileCopierNIO { public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } try ( FileChannel source = new FileInputStream(sourceFile).getChannel(); FileChannel destination = new FileOutputStream(destFile).getChannel() ) { destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); } } }
This code simplifies file copying to a single method call, eliminating the need for manual looping and stream handling. Moreover, it can be further simplified using the Files.copy() method from the NIO.2 package:
import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; public class FileCopierNIO2 { public static void copyFile(File sourceFile, File destFile) throws IOException { Path sourcePath = sourceFile.toPath(); Path destPath = destFile.toPath(); Files.copy(sourcePath, destPath, StandardCopyOption.REPLACE_EXISTING); } }
The Files.copy() method provides the same functionality as the FileChannel.transferFrom() method, but with a more concise syntax.
Benefits of NIO-Based Copying
The NIO-based approach to file copying offers several advantages over the traditional method:
The above is the detailed content of How to Efficiently Copy Files in Java without Manual Looping?. For more information, please follow other related articles on the PHP Chinese website!