Java读取文件的方式有很多种,方法越多反而不知道怎么使用,一般来说只需要掌握几个常用的读取方法就行了
按照用途的不同可以分为 读取单个字符,读取一行,读取整个文件等
下面介绍下如何读取整个文件的内容作为字符串,可用来读取json文件
public void test4() {
File file = new File("./A.json");
String s = readToString(file);
try {
A a = JSON.parseObject(s, A.class);
} catch (Exception e) {
e.printStackTrace();
}
}
public String readToString(File file) {
long length = file.length();
byte[] bytes = new byte[(int) length];
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
fileInputStream.read(bytes);
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return new String(bytes);// 使用默认的编码,可自行选择文件的编码
}