Java以行的方式,快速读取大文件的2种实现方法,附完整代码和测试结果

x33g5p2x  于2022-08-17 转载在 Java  
字(1.4k)|赞(0)|评价(0)|浏览(696)

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;

    }

}

测试结果:

相关文章