Java IO流中拷贝(复制)文件的写法

1. 使用字节流读写复制文件

/**

     * 字节流读写复制文件
     * @param src 源文件
     * @param out 目标文件
     */
    public static void InputStreamOutputStream(String src, String out) {
        FileOutputStream outputStream = null;
        FileInputStream inputStream = null;
        try {
            outputStream = new FileOutputStream(out);
            inputStream = new FileInputStream(src);
            byte[] bytes = new byte[1024];
            int num = 0;
            while ((num = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, num);
                outputStream.flush();
            }


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }


2.使用字符流读写复制文件

 /**
     * 字符流读写复制文件
     *
     * @param src 源文件
     * @param out 目标文件
     */
    public static void FileReaderFileWriter(String src, String out) {
        FileWriter fileWriter = null;
        FileReader fileReader = null;
        try {
            //创建一个可以往文件中写入字符数据的字符输出流对象。
                /*
                * 既然是往一个文件中写入文字数据,那么在创建对象时,就必须明确该文件(用于存储数据的目的
                * 地)。
                *
                * 如果文件不存在,则会自动创建。
                * 如果文件存在,则会被覆盖。
                *
                * 如果构造函数中加入true,可以实现对文件进行续写!
                */
            fileWriter = new FileWriter(out);
            //1,创建读取字符数据的流对象。
                /*
                * 在创建读取流对象时,必须要明确被读取的文件。一定要确定该文件是存在的。
                *
                * 用一个读取流关联一个已存在文件。
                */
            fileReader = new FileReader(src);


            //创建一个临时容器,用于缓存读取到的字符。
            char[] chars = new char[1024];
            //定义一个变量记录读取到的字符数,(其实就是往数组里装的字符个数 )
            int num = 0;
            while ((num = fileReader.read(chars)) != -1) {
                fileWriter.write(chars, 0, num);
                fileWriter.flush();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileWriter.close();
                fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值