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) {
this(FileUtil.file(filePath), charset);
}
public FileReader(File file, Charset charset) {
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 会发现
public String readString() throws IORuntimeException {
return new String(this.readBytes(), this.charset);
}
readBytes(),其实是将 file 转换为 byte[] 的过程
public byte[] readBytes() throws IORuntimeException {
long len = this.file.length();
if (len >= 21474837L) {
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);
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);
this.value = StringCoding.decode(charset, bytes, offset, length);
}
未完待续…