java中如何复制文件?

本示例演示如何使用Java IO库复制文件。在这里,我们将使用java.io.FileInputStream和串联的java.io.FileOutputStream类。

package org.nhooo.example.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopyDemo {
    public static void main(String[] args) {
        // 创建源文件和目标文件的实例
        File source = new File("source.pdf");
        File destination = new File("target.pdf");

        try (FileInputStream fis = new FileInputStream(source);
             FileOutputStream fos = new FileOutputStream(destination)) {
            // 定义用于缓冲文件数据的缓冲区大小
            byte[] buffer = new byte[4096];
            int read;
            while ((read = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}