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

前端 未结 21 2435
心在旅途
心在旅途 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:20

    What you can do is scan the entire text using Scanner and go through the text line by line. Of course you should import the following:

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    public static void readText throws FileNotFoundException {
        Scanner scan = new Scanner(new File("samplefilename.txt"));
        while(scan.hasNextLine()){
            String line = scan.nextLine();
            //Here you can manipulate the string the way you want
        }
    }
    

    Scanner basically scans all the text. The while loop is used to traverse through the entire text.

    The .hasNextLine() function is a boolean that returns true if there are still more lines in the text. The .nextLine() function gives you an entire line as a String which you can then use the way you want. Try System.out.println(line) to print the text.

    Side Note: .txt is the file type text.

提交回复
热议问题