文件拷贝

文件拷贝

代码:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 使用 FileInputStream + FileOutputStream 完成文件拷贝
 * 拷贝的过程:一边读,一边写
 * 使用以上字节流拷贝文件时,文件类型随意,万能的,什么类型文件均可拷贝
 */
public class Copy01 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        FileOutputStream fos = null;

        try {
            // 创建一个输入流对象
            fis = new FileInputStream("D:\\Blogs\\FileInputStream 终级版.md");
            // 创建一个输出流对象
            fos = new FileOutputStream("D:\\FileInputStream 终级版.md");

            // 核心:一边读,一边写
            byte[] bytes = new byte[1024 * 1024]; // 一次拷贝 1MB,即 1024 * 1024 (Byte)

            int readCount = 0;
            while((readCount = fis.read(bytes)) != -1){
                fos.write(bytes,0, readCount); // 读多少,写多少
            }
            // 刷新
            fos.flush();

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

            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 分开 try ... catch,不要一起
            // 一起 try ... catch 时,其中一个流出现异常时,可能导致另一个流无法关闭
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

运行结果:

在D盘根目录下可以找到拷贝进来的FileInputStream 终级版.md文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值