Java 逐行讀取文本文件的幾種方式以及效率對比

作者: Seven-Steven

原文鏈接: https://blog.diqigan.cn/posts/java-read-file-by-line.html

前言

上周負(fù)責(zé)的模塊中需要逐行讀取文件內(nèi)容, 寫完之后對程序執(zhí)行效率不太滿意, 索性上網(wǎng)查了一下 Java 逐行讀取文件內(nèi)容的各種方法, 并且簡單地比對了一下執(zhí)行效率. 在此記錄, 希望能夠幫到有需要的人.

注意: 本文比對的項目為 逐行讀取文本內(nèi)容, 并不能代表其他方式的文件讀取效率優(yōu)劣!!!

文末有完整代碼.

先放結(jié)果

1000000 行文本讀取結(jié)果比對:

BufferedReader 耗時: 49ms
Scanner 耗時: 653ms
Apache Commons IO 耗時: 44ms
InputStreamReader 耗時: 191ms
FileInputStream 耗時: 3171ms
BufferedInputStream 耗時: 70ms
FileUtils 耗時: 46ms
Files 耗時: 99ms

24488656 行文本讀取結(jié)果比對:

BufferedReader 耗時: 989ms
Scanner 耗時: 11899ms
Apache Commons IO 耗時: 568ms
InputStreamReader 耗時: 3377ms
FileInputStream 耗時: 78903ms
BufferedInputStream 耗時: 1480ms
FileUtils 耗時: 16569ms
Files 耗時: 25162ms

可見, 當(dāng)文件較小時:

  • ApacheCommonsIO 流 表現(xiàn)最佳;
  • FileUtils, BufferedReader 居其二;
  • BufferedInputStream, Files 隨其后;
  • InputStreamReader, Scanner, FileInputStream 略慢.

當(dāng)文件較大時, Apache Commons IO 流, BufferedReader 依然出色, Files, FileUtils 速度開始變慢.

簡要分析

使用到的工具類包括:

  • java.io.BufferedReader
  • java.util.Scanner
  • org.apache.commons.io.FileUtils
  • java.io.InputStreamReader
  • java.io.FileInputStream
  • java.io.BufferedInputStream
  • com.google.common.io.Files

其中:

Apache Commons IO 流BufferedReader 使用到了緩沖區(qū), 所以在不消耗大量內(nèi)存的情況下提高了處理速度;

FileUtilsFiles 是先把文件內(nèi)容全部讀入內(nèi)存, 然后在進行操作, 是典型的空間換時間案例. 這種方法可能會大量消耗內(nèi)存, 建議酌情使用;

其他幾個工具類本來就不擅長逐行讀取, 效率底下也是情理之中.

建議

在逐行讀取文本內(nèi)容的需求下, 建議使用 Apache Commons IO 流, 或者 BufferedReader, 既不會過多地占用內(nèi)存, 也保證了優(yōu)異的處理速度.

參考文獻:

附錄-源代碼:

import com.google.common.io.Files;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;

import java.io.*;
import java.util.List;
import java.util.Random;
import java.util.Scanner;

/**
 * @Description: 逐行讀取文件性能對比
 * @Author: Seven-Steven
 * @Date: 19-1-25
 **/
public class ReadByLineFromFileTest {

  public static void main(String[] args) {
    ReadByLineFromFileTest test = new ReadByLineFromFileTest();
    String filePath = "./testFile.txt";
    File file = new File(filePath);
    if (!file.exists()) {
      // 隨機寫入 1000000 行內(nèi)容
      test.writeRandom(filePath, 1000000);
    }

    long before, after, time;
    // 使用 BufferedReader 逐行讀取文件
    before = System.currentTimeMillis();
    test.bufferedReader(filePath);
    after = System.currentTimeMillis();
    time = after - before;
    System.out.println("BufferedReader 耗時: " + time + "ms");

    // 使用 Scanner 逐行讀取文件
    before = System.currentTimeMillis();
    test.scanner(filePath);
    after = System.currentTimeMillis();
    time = after - before;
    System.out.println("Scanner 耗時: " + time + "ms");

    // 使用 Apache Commons IO 流逐行讀取文件
    before = System.currentTimeMillis();
    test.apacheCommonsIo(filePath);
    after = System.currentTimeMillis();
    time = after - before;
    System.out.println("Apache Commons IO 耗時: " + time + "ms");

    // 使用 InputStreamReader 逐字符讀取文件
    before = System.currentTimeMillis();
    test.inputStreamReader(filePath);
    after = System.currentTimeMillis();
    time = after - before;
    System.out.println("InputStreamReader 耗時: " + time + "ms");

    // 使用 FileInputStream 逐字符讀取文件
    before = System.currentTimeMillis();
    test.fileInputStream(filePath);
    after = System.currentTimeMillis();
    time = after - before;
    System.out.println("FileInputStream 耗時: " + time + "ms");


    // 使用 BufferedInputStream 逐字符讀取文件
    before = System.currentTimeMillis();
    test.bufferedInputStream(filePath);
    after = System.currentTimeMillis();
    time = after - before;
    System.out.println("BufferedInputStream 耗時: " + time + "ms");

    // 使用 FileUtils 一次性讀取文件所有行
    before = System.currentTimeMillis();
    test.fileUtils(filePath);
    after = System.currentTimeMillis();
    time = after - before;
    System.out.println("FileUtils 耗時: " + time + "ms");

    // 使用 Files 一次性讀取文件所有行
    before = System.currentTimeMillis();
    test.files(filePath);
    after = System.currentTimeMillis();
    time = after - before;
    System.out.println("Files 耗時: " + time + "ms");
  }

  /**
   * @Description: 使用 Apache Commons IO 流逐行讀取文件
   * Maven 依賴:
   *         <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
   *         <dependency>
   *             <groupId>commons-io</groupId>
   *             <artifactId>commons-io</artifactId>
   *             <version>2.6</version>
   *         </dependency>
   * @Param: [filePath] 文件路徑
   * @Author: Seven-Steven
   * @Date: 19-1-24
   **/
  public void apacheCommonsIo(String filePath) {
    File file = new File(filePath);
    if (!file.exists()) {
      return;
    }

    try {
      LineIterator iterator = FileUtils.lineIterator(file, "UTf-8");
      while (iterator.hasNext()) {
        String line = iterator.nextLine();
        // TODO
        // System.out.println(line);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
   * @Description: 使用 Scanner 類逐行讀取
   * @Param: [filePath] 文件路徑
   * @Author: Seven-Steven
   * @Date: 19-1-24
   **/
  public void scanner(String filePath) {
    File file = new File(filePath);
    if (!file.exists()) {
      return;
    }

    FileInputStream fileInputStream = null;
    Scanner scanner = null;
    try {
      fileInputStream = new FileInputStream(file);
      scanner = new Scanner(fileInputStream, "UTF-8");

      while (scanner.hasNextLine()) {
        // TODO things
        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();
      }
    }
  }

  /**
   * @Description: 使用 Files 一次性讀取所有行
   * Maven 依賴:
   *         <!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
   *         <dependency>
   *             <groupId>com.google.guava</groupId>
   *             <artifactId>guava</artifactId>
   *             <version>r05</version>
   *         </dependency>
   * @Param: [filePath] 文件路徑
   * @Author: Seven-Steven
   * @Date: 19-1-24
   **/
  public void files(String filePath) {
    File file = new File(filePath);
    if (!file.exists()) {
      return;
    }

    try {
      List<String> fileLines = Files.readLines(file, Charsets.toCharset("UTF-8"));
      for (String str : fileLines) {
        // TODO things
        // System.out.println(str);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
   * @Description: 使用 FileUtils 一次性將文件所有行讀入內(nèi)存
   * Maven 依賴:
   *         <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
   *         <dependency>
   *             <groupId>commons-io</groupId>
   *             <artifactId>commons-io</artifactId>
   *             <version>2.6</version>
   *         </dependency>
   * @Param: [filePath] 文件路徑
   * @Author: Seven-Steven
   * @Date: 19-1-24
   **/
  public void fileUtils(String filePath) {
    File file = new File(filePath);
    if (!file.exists()) {
      return;
    }

    try {
      List<String> fileLines = FileUtils.readLines(file, Charsets.UTF_8);
      for (String str : fileLines) {
        // TODO
        // System.out.println(str);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public void bufferedInputStream(String filePath) {
    File file = new File(filePath);
    if (!file.exists()) {
      return;
    }

    FileInputStream fileInputStream = null;
    BufferedInputStream bufferedInputStream = null;
    try {
      fileInputStream = new FileInputStream(file);
      bufferedInputStream = new BufferedInputStream(fileInputStream);

      int temp;
      char character;
      String line = "";
      while ((temp = bufferedInputStream.read()) != -1) {
        character = (char) temp;
        if (character != '\n') {
          line += character;
        } else {
          // TODO
          // System.out.println(line);
          line = "";
        }
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (fileInputStream != null) {
        try {
          fileInputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }

      if (bufferedInputStream != null) {
        try {
          bufferedInputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }

  /**
   * @Description: 使用 FileInputStream 逐字符讀取文件
   * @Param: [filePath] 文件路徑
   * @Author: Seven-Steven
   * @Date: 19-1-23
   **/
  public void fileInputStream(String filePath) {
    File file = new File(filePath);
    if (!file.exists()) {
      return;
    }

    FileInputStream fileInputStream = null;
    try {
      fileInputStream = new FileInputStream(file);
      int temp;
      char character;
      String line = "";
      while ((temp = fileInputStream.read()) != -1) {
        character = (char) temp;
        if (character != '\n') {
          line += character;
        } else {
          // TODO
          // System.out.println(line);
          line = "";
        }
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (fileInputStream != null) {
        try {
          fileInputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }

  /**
   * @Description: 使用 InputStreamReader 逐行讀取文件
   * @Param: [filePath] 文件路徑
   * @Author: Seven-Steven
   * @Date: 19-1-23
   **/
  public void inputStreamReader(String filePath) {
    File file = new File(filePath);
    if (!file.exists()) {
      return;
    }

    FileInputStream fileInputStream = null;
    InputStreamReader inputStreamReader = null;
    try {
      fileInputStream = new FileInputStream(file);
      inputStreamReader = new InputStreamReader(fileInputStream);
      int temp;
      char character;
      String line = "";
      while ((temp = inputStreamReader.read()) != -1) {
        character = (char) temp;
        if (character != '\n') {
          line += character;
        } else {
          // TODO
          // System.out.println(line);
          line = "";
        }
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (fileInputStream != null) {
        try {
          fileInputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }

      if (inputStreamReader != null) {
        try {
          inputStreamReader.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }

  /**
   * @Description: 使用 BufferedReader 逐行讀取文件內(nèi)容
   * @Param: [filePath] 文件路徑
   * @Author: Seven-Steven
   * @Date: 19-1-23
   **/
  public void bufferedReader(String filePath) {
    File file = new File(filePath);
    if (!file.exists()) {
      return;
    }

    FileReader fileReader = null;
    BufferedReader bufferedReader = null;
    try {
      fileReader = new FileReader(file);
      bufferedReader = new BufferedReader(fileReader);

      String line = "";
      while ((line = bufferedReader.readLine()) != null) {
        // TODO things
        // System.out.println(line);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (fileReader != null) {
        try {
          fileReader.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }

      if (bufferedReader != null) {
        try {
          bufferedReader.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }

  /**
   * @Description: 隨機往文件中寫入 totalLines 行內(nèi)容
   * @Param: [filePath, totalLines] 文件路徑, 內(nèi)容行數(shù)
   * @Author: Seven-Steven
   * @Date: 19-1-23
   **/
  public void writeRandom(String filePath, int totalLines) {
    RandomAccessFile file = null;
    Random random = new Random();
    try {
      file = new RandomAccessFile(filePath, "rw");
      long length = file.length();
      for (int i = 0; i < totalLines; i++) {
        file.seek(length);
        int number = random.nextInt(1000000);
        String line = number + "\n";
        file.writeBytes(line);
        length += line.length();
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (file != null) {
        try {
          file.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末宙地,一起剝皮案震驚了整個濱河市龄句,隨后出現(xiàn)的幾起案子誊酌,更是在濱河造成了極大的恐慌,老刑警劉巖蹭睡,帶你破解...
    沈念sama閱讀 218,640評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異赶么,居然都是意外死亡肩豁,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,254評論 3 395
  • 文/潘曉璐 我一進店門禽绪,熙熙樓的掌柜王于貴愁眉苦臉地迎上來蓖救,“玉大人,你說我怎么就攤上這事印屁⊙啵” “怎么了?”我有些...
    開封第一講書人閱讀 165,011評論 0 355
  • 文/不壞的土叔 我叫張陵雄人,是天一觀的道長从橘。 經(jīng)常有香客問我念赶,道長,這世上最難降的妖魔是什么恰力? 我笑而不...
    開封第一講書人閱讀 58,755評論 1 294
  • 正文 為了忘掉前任叉谜,我火速辦了婚禮,結(jié)果婚禮上踩萎,老公的妹妹穿的比我還像新娘停局。我一直安慰自己,他們只是感情好香府,可當(dāng)我...
    茶點故事閱讀 67,774評論 6 392
  • 文/花漫 我一把揭開白布董栽。 她就那樣靜靜地躺著,像睡著了一般企孩。 火紅的嫁衣襯著肌膚如雪锭碳。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,610評論 1 305
  • 那天勿璃,我揣著相機與錄音擒抛,去河邊找鬼。 笑死补疑,一個胖子當(dāng)著我的面吹牛歧沪,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播癣丧,決...
    沈念sama閱讀 40,352評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼槽畔,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了胁编?” 一聲冷哼從身側(cè)響起厢钧,我...
    開封第一講書人閱讀 39,257評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎嬉橙,沒想到半個月后早直,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,717評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡市框,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,894評論 3 336
  • 正文 我和宋清朗相戀三年霞扬,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片枫振。...
    茶點故事閱讀 40,021評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡喻圃,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出粪滤,到底是詐尸還是另有隱情斧拍,我是刑警寧澤,帶...
    沈念sama閱讀 35,735評論 5 346
  • 正文 年R本政府宣布杖小,位于F島的核電站肆汹,受9級特大地震影響愚墓,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜昂勉,卻給世界環(huán)境...
    茶點故事閱讀 41,354評論 3 330
  • 文/蒙蒙 一浪册、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧岗照,春花似錦村象、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,936評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至嗓袱,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間习绢,已是汗流浹背渠抹。 一陣腳步聲響...
    開封第一講書人閱讀 33,054評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留闪萄,地道東北人梧却。 一個月前我還...
    沈念sama閱讀 48,224評論 3 371
  • 正文 我出身青樓,卻偏偏與公主長得像败去,于是被迫代替她去往敵國和親放航。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,974評論 2 355

推薦閱讀更多精彩內(nèi)容