1.文件流读取,能满足大部分需求
//读取json文件
public static String readJsonFile(String fileName) {
String jsonStr = "";
try {
File jsonFile = new File(fileName);
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
这个效率是不是有待改进,如果需要改进,请继续往下看。
2.Apache Commons IO流读取
public static String readJsonFile2(String filename){
LineIterator it = null;
StringBuffer sb = new StringBuffer();
try {
it = FileUtils.lineIterator(new File(filename), "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
try {
while (it.hasNext()) {
String line = it.nextLine();
// do something with line
sb.append(line);
}
} finally {
LineIterator.closeQuietly(it);
}
return sb.toString();
}
从3433ms->838ms,这提升的不是一点半点了,guava读取、Apache Commons IO普通方式可以自己
试着 去尝试比较下,根据cpu消耗、内存占用、处理速度方面综合选择设计自己需求的读取方式。