java指定路径的非文本文件复制

这段代码演示了如何使用BufferedInputStream和BufferedOutputStream在Java中高效地从源文件复制到目标文件。它通过创建输入和输出流的缓冲版本,然后读取和写入字节块来实现文件的复制,提高了文件操作的性能。
摘要由CSDN通过智能技术生成

将此代码拷入程序里,调用该方法即可
srcPath:源文件路径
destPath:目标文件路径

public void copyFileWithBuffered(String srcPath, String destPath) {
        BufferedInputStream bfis = null;
        BufferedOutputStream bfos = null;

        try {
            //1 原文件对象
            File srcFile = new File(srcPath);
            File destFile = new File(destPath);

            //2 流对象
            //3节点流
            FileInputStream fis = new FileInputStream(srcFile);
            FileOutputStream fos = new FileOutputStream(destFile);
            //4 缓冲流
            bfis = new BufferedInputStream(fis);
            bfos = new BufferedOutputStream(fos);

            //5 读写操作
            byte[] buffer = new byte[1024];
            int len;
            while ((len = bfis.read(buffer)) != -1) {
                bfos.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //6 关闭外层流,内层节点流会自动关闭
            if (bfis != null) {
                try {
                    bfis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bfos != null) {
                try {
                    bfos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值