How to loop to copy a file in Java

In Java, you can use the Files class in the java.nio.file package to copy files. By looping through the content of the source file and writing it to the target file, you can achieve file copying. Below is an example code:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public class FileCopy {
    public static void main(String[] args) {
        Path sourceFile = Path.of("source.txt"); // 源文件路径
        Path targetFile = Path.of("target.txt"); // 目标文件路径

        try {
            // 使用循环复制文件
            Files.copy(sourceFile, targetFile, StandardCopyOption.REPLACE_EXISTING);

            System.out.println("文件复制成功!");
        } catch (IOException e) {
            System.out.println("文件复制失败:" + e.getMessage());
        }
    }
}

In the code above, we are utilizing the Files.copy() method to duplicate a file. This method takes three parameters: the source file path, the target file path, and the copy option. Specifically, StandardCopyOption.REPLACE_EXISTING signifies that if the target file already exists, it will be replaced.

Please note that the code above is just a simple example and does not involve using loops to copy files. If you want to copy files in a loop, you can use a loop structure (such as for or while) to control the number of copies.

bannerAds