作者: 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)存的情況下提高了處理速度;
FileUtils
和 Files
是先把文件內(nèi)容全部讀入內(nèi)存, 然后在進行操作, 是典型的空間換時間案例. 這種方法可能會大量消耗內(nèi)存, 建議酌情使用;
其他幾個工具類本來就不擅長逐行讀取, 效率底下也是情理之中.
建議
在逐行讀取文本內(nèi)容的需求下, 建議使用 Apache Commons IO 流, 或者 BufferedReader, 既不會過多地占用內(nèi)存, 也保證了優(yōu)異的處理速度.
參考文獻:
- [Java]讀取文件方法大全 --- lovebread
- java讀取文件API速度對比 --- fengxingzhe001
- Java高效讀取大文件 --- Eugen Paraschiv[文] / ImportNew - 進林[譯]
附錄-源代碼:
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();
}
}
}
}
}