java关于IO流读取性能测试
关于io及其原理百度,这里直接上测试代码。
博主最常用的三种方式分别是:InputStreamReader、Scanner和LineIterator,下面看测试demo。
public static void main(String[] args) throws IOException {
long start1 = System.currentTimeMillis();
StringBuffer sb = null;
try(InputStreamReader reader = new InputStreamReader(
new FileInputStream("C:\\Users\\lenovo\\Desktop\\新建文本文档.txt"), StandardCharsets.UTF_8);){
sb = new StringBuffer();
String lineText;
BufferedReader bufferedReader = new BufferedReader(reader);
while ((lineText = bufferedReader.readLine()) != null){
sb.append(lineText).append("\n");
}
}catch (Exception e){
System.out.println("读取失败");
}
System.out.println("BufferedReader读取完成,耗时" + (System.currentTimeMillis() - start1));
// try(OutputStreamWriter writer = new OutputStreamWriter(
// new FileOutputStream("C:\\Users\\lenovo\\Desktop\\新建文本文档555.txt"), StandardCharsets.UTF_8);){
// BufferedWriter out = new BufferedWriter(writer);
// out.write(String.valueOf(sb));
// out.flush();
// }catch (Exception e){
// System.out.println("写入失败");
// }
long start2 = System.currentTimeMillis();
Scanner sc;
StringBuffer sb2 = new StringBuffer();
try(FileInputStream inputStream = new FileInputStream("C:\\Users\\lenovo\\Desktop\\新建文本文档.txt");) {
sc = new Scanner(inputStream, "UTF-8");
while (sc.hasNextLine()) {
sb2.append(sc.nextLine()).append("\n");
}
System.out.println("Scanner读取完成,耗时" + (System.currentTimeMillis() - start2));
if (sc.ioException() != null) {
throw sc.ioException();
}
} catch (IOException e) {
e.printStackTrace();
}
long start3 = System.currentTimeMillis();
LineIterator it = FileUtils.lineIterator(new File("C:\\Users\\lenovo\\Desktop\\新建文本文档.txt"), "UTF-8");
StringBuffer sb3 = new StringBuffer();
try {
while (it.hasNext()) {
sb3.append(it.nextLine()).append("\n");
}
System.out.println("LineIterator读取完成,耗时" + (System.currentTimeMillis() - start3));
} finally {
LineIterator.closeQuietly(it);
}
}
测试结果:
测试文件大小为11.6M
BufferedReader读取完成,耗时136ms
Scanner读取完成,耗时2414ms
LineIterator读取完成,耗时118ms
正常工作建议使用BufferedReader或者LineIterator就可以满足,由于scanner是将读取内容放在内存中,所以读取较大的文件时不建议使用。