使用字节输入流(InputStream)与输出流(OutputStream)实现文件拷贝操作

实现思路:

  1.先确定需要复制文件的路径和粘贴文件地路径,创建File对象。

  2.然后创建InputStream字节输入流对象逐一依次将指定复制的文件内容一一输入程序中来。

  3.最后将程序接收到的数据一一用OutputStream字节输出流输出到指定粘贴的文件中。

代码实现:

import java.io.*;

public class FileCopy {
    public static void main(String[] args) {
        //确定需要复制文件的路径和粘贴文件地路径
        String srcFilePath = "D:\\test01.jpg";
        String destFilePath = "D:\\test\\test02.jpg";
        //创建文件输入流对象与输出流对象
        InputStream input = null;
        OutputStream output = null;
        try {
            //创建实例对象
            input = new FileInputStream(srcFilePath);
            output = new FileOutputStream(destFilePath);
            //定义字节数组用于一次性IO流操作的空间大小
            byte[] buffer = new byte[1024];
            //定义int每次接收字节输入流实际每次读取的空间大小长度
            int len = 0;
            //使用循环依次读取buffer空间大小的数据
            //直到read未读取到任何数据返回-1时停止循环,即停止读取
            while((len = input.read(buffer)) != -1){
                //将每次读取到的数据输出到字节输出流中指定的数据对象中
                output.write(buffer,0,len);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //关闭输入流与输出流对象,释放资源
            if (output != null){
                try {
                    output.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (input != null){
                try {
                    input.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

T何必当初

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值