Java大文件读取

时间:2025-02-21 19:59:23

1.内存读取

import ;
import ;
import ;
import ;

import ;
import ;
import ;

public class Reading {


    public static void main(String[] args) {

        try {
            List<String> lineOfApacheIO = (new File("File Path"));

            List<String> linesOfIoUtils = (new FileInputStream(new File("File Path")), Charsets.UTF_8);

            List<String> lineOfGuava = (new File("File Path"), Charsets.UTF_8);
        } catch (Exception e){

        }

    }
}

内存占用较大

2. 流式读取

        try (FileInputStream inputStream = new FileInputStream("File Path");
             Scanner sc = new Scanner(inputStream, "UTF-8")){
            while (()){
                String line = ();
            }
            
            if (() != null){
                //occur error when scan
                throw ();
            }
        } catch (FileNotFoundException e){
            ("file is not found");
        } catch (IOException e){
            ("file read occur error");
        } catch (Exception e){
            ("occur error");
        }

内存占用小

3.第三方流式读取

import ;
import .slf4j.Slf4j;
import ;
import ;
import ;
import ;

import ;
import ;
import ;
import ;

	public static void main(String[] args){
        LineIterator lines = (new FileInputStream("File Path"), Charsets.UTF_8);
        while (()){
            ();
        }
    }

同上