Java几种文件拷贝方式

第一种

使用 java.io 包下的库,使用 FileInputStream 读取,再使用 FileOutputStream写出。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopy {
    public static void main(String[] args) {
        String sourceFilePath = "source.txt";
        String targetFilePath = "target.txt";

        try (FileInputStream inputStream = new FileInputStream(sourceFilePath);
             FileOutputStream outputStream = new FileOutputStream(targetFilePath)) {

            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            System.out.println("文件拷贝完成");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

第二种

利用 java.nio 包下的库,使用 transferTo 或 transfFrom 方法实现。
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileCopy {
    public static void main(String[] args) {
        String sourceFilePath = "source.txt";
        String targetFilePath = "target.txt";

        Path sourcePath = Paths.get(sourceFilePath);
        Path targetPath = Paths.get(targetFilePath);

        try (FileChannel sourceChannel = FileChannel.open(sourcePath);
             FileChannel targetChannel = FileChannel.open(targetPath)) {

            long transferredBytes = sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);

            System.out.println("文件拷贝完成,已传输 " + transferredBytes + " 字节");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

第三种

Java 标准类库本身已经提供了 Files.copy 的实现。

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

public class FileCopy {
    public static void main(String[] args) {
        String sourceFilePath = "source.txt";
        String targetFilePath = "target.txt";

        Path sourcePath = Paths.get(sourceFilePath);
        Path targetPath = Paths.get(targetFilePath);

        try {
            Files.copy(sourcePath, targetPath);
            System.out.println("文件拷贝完成");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

哪一种效率最高

对于 Copy 的效率,这个其实与操作系统和配置等情况相关,在传统的文件 IO 操作里面,我们都是调用操作系统提供的底层标准 IO 系统调用函数read()、write() ,由于内核指令的调用会使得当前用户线程切换到内核态,然后内核线程负责把相应的文件数据读取到内核的 IO 缓冲区,再把数据从内核IO缓冲区拷贝到进程的私有地址空间中去,这样便完成了一次IO操作。而 NIO 里面提供的 NIO transferTo 和 transfFrom 方法,也就是常说的零拷贝实现。它能够利用现代操作系统底层机制,避免不必要拷贝和上下文切换,因此在性能上表现比较好 
零拷贝(Zero-Copy)是一种优化文件复制操作的技术,它通过减少数据在内核空间和用户空间之间的传输次数来提高性能。

你可能感兴趣的:(java面试题,java,开发语言)