JAVA文件复制一些简单的方法

本文介绍了在Java中使用三种不同方式复制文件的方法:利用JDK 1.7及以上版本的Files类,通过Apache Commons IO包中的FileUtils类,以及采用FileChannel进行文件通道复制。每种方法都附有详细的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

jdk1.7以上有文件复制方法直接用

import java.nio.file.Files;
private static void copyFileTest(File oldFile, File newFile) {    
            try {
                Files.copy(oldFile.toPath(), newFile.toPath());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }

使用Apache Commons IO包中的FileUtils.copyFile方法复制

import org.apache.commons.io.FileUtils;
private static void copyFileTest(File oldFile, File newFile) {    
            try {
                FileUtils.copyFile(oldFile, newFile);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }

文件通道(FileChannel)来实现文件复制

import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel;

public static void copyFileTest(File oldFile, File newFile) {
    if(!newFile.getParentFile().exists())//判断有没有父路径,就是判断文件整个路径是否存在
        newFile.getParentFile().mkdirs();//不存在就全部创建
    FileOutputStream fo = null;
    FileInputStream fi = null;
    FileChannel out = null;
    FileChannel in = null;
    try {
        fo = new FileOutputStream(newFile);
        fi = new FileInputStream(oldFile);
        in = fi.getChannel();
        out = fo.getChannel();
        /*ByteBuffer bb;
        bb = in.map(MapMode.READ_ONLY, 0,in.size()).load();
        out.write(bb);*/
        in.transferTo(0, in.size(), out);//从in读取,然后写入out。前三行注释的代码也可以直接复制
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally {
        try {
            fi.close();
            in.close();
            fo.close();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值