java_IO流Buffered拷贝

使用BufferedReader 和 BufferedWriter 完成文本文件拷贝

package com.hspedu.writer_;

import java.io.*;

public class BufferedCopy_ {
    public static void main(String[] args) {

        //BufferedReader 和BufferedWriter 是按照字符操作
        //不要去操作二进制文件(声音,视频,doc,pdf),可能造成文件损坏
        String srcFilePath = "e:\\new3.txt";
        String destFilePath = "e:\\news3.txt";
        BufferedReader br = null;
        BufferedWriter bw = null;
        String line;
        try {
            br = new BufferedReader(new FileReader(srcFilePath));
            bw = new BufferedWriter(new FileWriter(destFilePath));

            //读取文件
            //readLine 读取一行内容,没有换行
            while ((line = br.readLine()) != null) {
                //每读取一行就写入
                bw.write(line);
                //插入一个换行符
                bw.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭流
            try {
                if(br != null) {
                    br.close();
                }
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

BufferedOutputStream 和 BufferedInputStream使用

package com.hspedu.outputstream_;

import java.io.*;

//演示使用BufferedOutputStream 和 BufferedInputStream使用
//完成二进制拷贝
//也可以操作文本文件
public class BufferedCopy02 {
    public static void main(String[] args) {

        String srcFilePath = "e:\\aa.png";
        String destFilePath = "d:\\aa.png";

        //创建BufferedOutputStream 和 BufferedInputStream对象
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            //因为 FileInputStream 是 InputStream 子类
            bis = new BufferedInputStream(new FileInputStream(srcFilePath));
            bos = new BufferedOutputStream(new FileOutputStream(destFilePath));

            //循环读取文件,并写入到destFilePath
            byte[] buff = new byte[1024];
            int readLine = 0;
            //当返回-1时,文件读取完毕
            while((readLine = bis.read(buff)) != -1) {
                bos.write(buff, 0, readLine);
            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭外层处理流,底层会去关闭节点流
            try {
                if(bis != null) {
                    bis.close();
                }
                if(bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值