Hutool工具类关于FileReader文件读取的见解

文件读取-FileReader

有需求是读取 json 文件并导出excel,由于用到了 FileReader, 体会到其强大的读取文件的能力。所以深入源码理解其原理。

FileReader fileReader = new FileReader(filename);
String fileContent = fileReader.readString();

简单的两行代码就能实现读取文件并转换为 String, 何其强大。

先来看看 FileReader 的构造函数

public FileReader(String filePath) {
    this(filePath, DEFAULT_CHARSET);
}

public FileReader(String filePath, Charset charset) {
    //这里其实调用的是 java.io.File
    this(FileUtil.file(filePath), charset);
}

public FileReader(File file, Charset charset) {
    //super方法这里调用类 FileWrapper 构造方法
    super(file, charset);
    //检查是否为 文件
    this.checkFile();
}

FileWrapper 构造方法

public FileWrapper(File file, Charset charset) {
    this.file = file;
    this.charset = charset;
}

FileReader 继承自 FileWrapper

package cn.hutool.core.io.file;

public class FileReader extends FileWrapper

FileWrapper 类中的属性

public class FileWrapper implements Serializable {
    private static final long serialVersionUID = 1L;
    protected File file;
    protected Charset charset;
    public static final Charset DEFAULT_CHARSET;
    
    //...
}

查看 readString 会发现

//FileReader类

public String readString() throws IORuntimeException {
    //这个 String 是调用 java.lang.String,将字节数组转为字符的过程
    return new String(this.readBytes(), this.charset);
}

readBytes(),其实是将 file 转换为 byte[] 的过程

public byte[] readBytes() throws IORuntimeException {
        long len = this.file.length();
        if (len >= 2147483647L) {
            throw new IORuntimeException("File is larger then max array size");
        } else {
            byte[] bytes = new byte[(int)len];
            FileInputStream in = null;

            try {
                in = new FileInputStream(this.file);
                //file 转为 byte[]
                int readLength = in.read(bytes);
                if ((long)readLength < len) {
                    throw new IOException(StrUtil.format("File length is [{}] but read [{}]!", new Object[]{len, readLength}));
                }
            } catch (Exception var10) {
                throw new IORuntimeException(var10);
            } finally {
                IoUtil.close(in);
            }

            return bytes;
        }
    }

java.lang.String

public String(byte bytes[], Charset charset) {
    this(bytes, 0, bytes.length, charset);
}

public String(byte bytes[], int offset, int length, Charset charset) {
    if (charset == null)
        throw new NullPointerException("charset");
    checkBounds(bytes, offset, length);
    //StringCoding.decode 解码,将字节转为字符的过程
    this.value =  StringCoding.decode(charset, bytes, offset, length);
}

未完待续…

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值