IO流实现"文件克隆"

3 篇文章 0 订阅

文件克隆
例题一:使用带缓冲区的字节流实现文件的克隆。
使用BufferedInputStreamBufferedOutputStream来实现文件的复制

import java.io.*;
/**
 * 添加缓冲区之后的字节流的拷贝
 */
public class TestCopy2 {
    public static void main(String[] args) {
        copy("源文件",",目标文件");
    }

    public static void copy(String src,String data){
        BufferedInputStream bis=null;
        BufferedOutputStream bos=null;
        //选择流
        try {
            bis=new BufferedInputStream(new FileInputStream(src));
            bos=new BufferedOutputStream(new FileOutputStream(data));
            //使用流
            byte[] bytes=new byte[1024];
            //定义一次读取的容量长度
            int len=0;
            while ((len=bis.read(bytes))!=-1){
                //写数据
                bos.write(bytes,0,len);
                //手动刷新,以防忘关流
                bos.flush();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            //关闭输入流
            try {
                if(bis!=null)
                    bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //关闭输出流
            try {
                if (bos!=null)
                    bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

例题二:使用带缓冲区的字符流实现文件的克隆
使用BufferedReader和BufferedWriter来实现文件的复制

import java.io.*;
/**
 * 带缓冲区字符流
 */
public class TestCopy3 {
    public static void main(String[] args) {
    bfCopy("源文件","目标文件");

    }
    public static void  bfCopy(String src,String date){
        //选择流
        BufferedReader br=null;
        BufferedWriter bw=null;
        try {
            br=new BufferedReader(new FileReader(src));
            bw=new BufferedWriter(new FileWriter(date));

            //声明一个字符数组
            char[] flag=new char[1024];
            //用来获取文件中字节的个数
            int len;
            //直到读取到最后长度为-1
            while ((len=br.read(flag))!=-1){
                //写数据
                bw.write(flag,0,len);
                bw.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            //关闭流
            try {
                if (br!=null){
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (bw!=null){
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值