java复制文件的方法有哪些 三种常见方法介绍

在 Java 中,有多种方法可以复制文件。以下是其中几种方法:

  1. 使用 Files 类的 copy() 方法:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;

public class FileCopyExample {
    public static void main(String[] args) {
        Path source = Paths.get("path/to/source/file");
        Path destination = Paths.get("path/to/destination/file");

        try {
            Files.copy(source, destination);
            System.out.println("File copied successfully.");
        } catch (IOException ex) {
            System.err.println("Error copying file: " + ex.getMessage());
        }
    }
}
  1. 使用 InputStream 和 OutputStream 复制文件:
import java.io.*;

public class FileCopyExample {
    public static void main(String[] args) {
        File source = new File("path/to/source/file");
        File destination = new File("path/to/destination/file");

        try (InputStream in = new FileInputStream(source);
             OutputStream out = new FileOutputStream(destination)) {

            // 缓冲区大小 4KB
            byte[] buffer = new byte[4096];

            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }

            System.out.println("File copied successfully.");
        } catch (IOException ex) {
            System.err.println("Error copying file: " + ex.getMessage());
        }
    }
}
  1. 使用 Apache Commons IO 库:
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;

public class FileCopyExample {
    public static void main(String[] args) {
        File source = new File("path/to/source/file");
        File destination = new File("path/to/destination/file");

        try {
            FileUtils.copyFile(source, destination);
            System.out.println("File copied successfully.");
        } catch (IOException ex) {
            System.err.println("Error copying file: " + ex.getMessage());
        }
    }
}

以上这些都是比较常用的复制文件的方法,可以根据实际情况选择使用其中的任何一个。

未经允许不得转载:国外服务器评测 » java复制文件的方法有哪些 三种常见方法介绍