Java 逐行读取文本文件的几种方式以及效率对比

前言

上周负责的模块中需要逐行读取文件内容, 写完之后对程序执行效率不太满意, 索性上网查了一下 Java 逐行读取文件内容的各种方法, 并且简单地比对了一下执行效率. 在此记录, 希望能够帮到有需要的人.

注意: 本文比对的项目为 逐行读取文本内容, 并不能代表其他方式的文件读取效率优劣!!!

文末有完整代码.

先放结果

1000000 行文本读取结果比对:

1
2
3
4
5
6
7
8
BufferedReader 耗时: 49ms
Scanner 耗时: 653ms
Apache Commons IO 耗时: 44ms
InputStreamReader 耗时: 191ms
FileInputStream 耗时: 3171ms
BufferedInputStream 耗时: 70ms
FileUtils 耗时: 46ms
Files 耗时: 99ms

24488656 行文本读取结果比对:

1
2
3
4
5
6
7
8
BufferedReader 耗时: 989ms
Scanner 耗时: 11899ms
Apache Commons IO 耗时: 568ms
InputStreamReader 耗时: 3377ms
FileInputStream 耗时: 78903ms
BufferedInputStream 耗时: 1480ms
FileUtils 耗时: 16569ms
Files 耗时: 25162ms

可见, 当文件较小时:

  • ApacheCommonsIO 流 表现最佳;
  • FileUtils, BufferedReader 居其二;
  • BufferedInputStream, Files 随其后;
  • InputStreamReader, Scanner, FileInputStream 略慢.

当文件较大时, 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 使用到了缓冲区, 所以在不消耗大量内存的情况下提高了处理速度;

FileUtilsFiles 是先把文件内容全部读入内存, 然后在进行操作, 是典型的空间换时间案例. 这种方法可能会大量消耗内存, 建议酌情使用;

其他几个工具类本来就不擅长逐行读取, 效率底下也是情理之中.

建议

在逐行读取文本内容的需求下, 建议使用 Apache Commons IO 流, 或者 BufferedReader, 既不会过多地占用内存, 也保证了优异的处理速度.

参考文献:

  • [Java]读取文件方法大全 — lovebread
  • java读取文件API速度对比 — fengxingzhe001
  • Java高效读取大文件 — Eugen Paraschiv[文] / ImportNew - 进林[译]

附录-源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
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 行内容
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 一次性将文件所有行读入内存
* 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 逐行读取文件内容
* @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 行内容
* @Param: [filePath, totalLines] 文件路径, 内容行数
* @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();
}
}
}
}
}