java中文件拷贝的几种方式

作者: adm 分类: java 发布时间: 2022-11-01

1.使用文件工具类静态方法直接拷贝

public static void copyFileByStream(File file, File fileTo) throws IOException {
        Files.copy(file.toPath(), fileTo.toPath());
}

2.传统FileOutPutStream拷贝

 //传统文件拷贝方式,通过FileInputStream和FileOutputStream实现
    public static void copyFileByStream(File file, File fileTo) throws IOException {
        InputStream in = new FileInputStream(file);
        OutputStream out = new FileOutputStream(fileTo);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = in.read(buffer)) > 0) {
            out.write(buffer, 0, length);
        }
    }

3.使用nio的“管道思想”,通过transferFrom和transferTo实现

 //基于nio的transferTo和transferFrom实现
    public static void copyFileByChannel(File file, File fileTo) throws IOException {
        FileChannel fileChannel = new FileInputStream(file).getChannel();
        FileChannel fileChannelTo = new FileOutputStream(fileTo).getChannel();
        for (long count = fileChannel.size(); count > 0; ) {
            long transferred = fileChannel.transferTo(fileChannel.position(), count, fileChannelTo);
            count -= transferred;
        }
    }

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!