读取大文件性能测试

发表于:2015-9-28 12:54

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:唐凯    来源:51Testing软件测试网采编

  读取大文件的方法这里有三种,
  第一种,使用commons-io的FileUtils的类进行读取
  第二种,使用Scanner进行读取
  第三种,使用cache进行读取
  读取文件大小:102M
  使用commons-io的FileUtils类进行读取
  public static void testReadFile() {
  try {
  LineIterator lineIterator = FileUtils.lineIterator(new File("D:/test.log"), "UTF-8");
  while (lineIterator.hasNext()) {
  String line = lineIterator.nextLine();
  System.out.println(line);
  }
  } catch (IOException e) {
  e.printStackTrace();
  }
  }
  读取时间在8秒左右
  使用Scanner进行读取:
public static void testScannerReadFile() {
FileInputStream fileInputStream = null;
Scanner scanner = null;
try {
fileInputStream = new FileInputStream("D:/test.log");
scanner = new Scanner(fileInputStream, "UTF-8");
while (scanner.hasNext()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (scanner != null) {
scanner.close();
}
}
}
  读取时间在10秒左右
  使用cache读取
public static void readCache() {
String filename = "D:/test.log";
File file = new File(filename);
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file), 10 * 1024 * 1024);   //读大文件 设置缓存
String tempString = null;
while ((tempString = reader.readLine()) != null) {
System.out.println(tempString);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
  读取时间在8秒左右,与commons-io的FileUtils不相上下,我这边暂时没有更大的文件进行比较如果,有更大的文件,欢迎进行测试比较。
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号