Java IO流-节点流-文件字节流和文件字符流封装FileUtil

Java IO流 -> 文件字节流和文件字符流封装FileUtil

import java.io.*;

public class FileUtil {
    private InputStream in;
    private OutputStream out;
    
    private Reader read;
    private Writer write;
    
    private int size = 1024;

    public FileUtil(){
    }

    public FileUtil(FileReader read, FileWriter write){
        super();
        this.read = read;
        this.write = write;
    }
    
    public FileUtil(InputStream in, OutputStream out) {
        super();
        this.in = in;
        this.out = out;
    }

    /**
     * 通过文件字符流实现文件的拷贝
     * @param srcFile
     * @param destFile
     */
    public void copyTxt(String srcFile, String destFile){
        try{
            this.read = new FileReader(srcFile);
            this.write = new FileWriter(destFile);
            this.copyTxt();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 字符数据流的拷贝
     */
    public void copyTxt(){
        if(read == null || write == null){
            throw new RuntimeException("输入输出流不可以为空!");
        }
        try{
            char[] buf = new char[size];
            for(int len = -1; (len = read.read(buf)) != -1; len++){
                write.write(buf,0,len);
            }
            write.flush();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            this.close(write,read);
        }
    }

    /**
     * 通过文件字节流实现文件的拷贝
     * @param srcFile
     * @param destFile
     */
    public void copy(String srcFile, String destFile){
        try{
            this.in = new FileInputStream(srcFile);
            this.out = new FileOutputStream(destFile);
            this.copy();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }
    }

    /**
     * 字节数据流的拷贝
     */
    public void copy(){
        if(in == null || out == null){
            throw new RuntimeException("输入输出流不可以为空!");
        }
        try{
            byte[] buf = new byte[size];
            for(int len = -1; (len = in.read(buf)) != -1; len++){
                out.write(buf,0,len);
            }
            out.flush();
        }catch(IOException e){
            e.printStackTrace();
        }finally {
            this.close(out,in);
        }
    }

    /**
     * 释放资源
     * @param args (可变参数)
     */
    private void close(Closeable ... args){
        for(Closeable closeable : args){
            try{
                if(closeable != null){
                    closeable.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值