Java读取1272447行数据,存入List中,用时:396毫秒。
直接上代码,已做备忘。
代码如下:
package com.example.springbootdownloadfile.file;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class ReadFileUtil {
public static void main(String[] args) {
long start=System.currentTimeMillis();
String fileName="E:\\resource\\res2.txt";
List<String> list=fileReadToArray(fileName);
long start2=System.currentTimeMillis();
System.out.println("读取"+list.size()+"行,用时:"+(start2-start)+"毫秒");
list=inputStreamReadertoArray(fileName);
long start3=System.currentTimeMillis();
System.out.println("读取"+list.size()+"行,用时:"+(start3-start2)+"毫秒");
}
public static List fileReadToArray(String filePath) {
// 使用ArrayList来存储每行读取到的字符串
List arrayList = new ArrayList<>();
try {
FileReader f = new FileReader(filePath);
BufferedReader b = new BufferedReader(f);
String s;
//判断是否到一行字符串
while ((s = b.readLine()) != null) {
arrayList.add(s);
}
b.close();
f.close();
} catch (IOException e) {
e.printStackTrace();
}
return arrayList;
}
public static List<String> inputStreamReadertoArray(String filePath) {
List<String> arrayList = new ArrayList<>();
try {
File file = new File(filePath);
InputStreamReader i = new InputStreamReader(new FileInputStream(file));
BufferedReader b = new BufferedReader(i);
// 按行读取字符串
String s;
while ((s = b.readLine()) != null) {
arrayList.add(s);
}
b.close();
i.close();
} catch (IOException e) {
e.printStackTrace();
}
return arrayList;
}
}
测试结果:
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://onefire.blog.csdn.net/article/details/126018245
内容来源于网络,如有侵权,请联系作者删除!