文件读取-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);
}
未完待续…