How can I read a large text file line by line using Java?

前端 未结 21 2357
心在旅途
心在旅途 2020-11-21 05:48

I need to read a large text file of around 5-6 GB line by line using Java.

How can I do this quickly?

21条回答
  •  长情又很酷
    2020-11-21 06:22

    The clear way to achieve this,

    For example:

    If you have dataFile.txt on your current directory

    import java.io.*;
    import java.util.Scanner;
    import java.io.FileNotFoundException;
    
    public class readByLine
    {
        public readByLine() throws FileNotFoundException
        {
            Scanner linReader = new Scanner(new File("dataFile.txt"));
    
            while (linReader.hasNext())
            {
                String line = linReader.nextLine();
                System.out.println(line);
            }
            linReader.close();
    
        }
    
        public static void main(String args[])  throws FileNotFoundException
        {
            new readByLine();
        }
    }
    

    The output like as below,

提交回复
热议问题