What is the fastest way to read a file in Java?


What is the fastest way to read a file in Java?


I am reading my file using the Scanner class. My code is below:

import java.io.*;
import java.util.Scanner;

class  filereader
    public static void main(String[] args) 

          Scanner sc = new Scanner(new FileReader("myfile.txt"));

        while (sc.hasNextLine()) {
        String text = sc.nextLine();
                //Business code here

        }catch(Exception e){
            System.out.println("Error is: "+ e.getMessage());


I have to read text file of 10GB and then process the lines for getting the data. Let's know the fasted way of reading the text.


View Answers

February 14, 2015 at 5:40 PM

Since you have to read the text file of big size you should use the BufferedReader class of Java.

Here is the sample code you can use:

FileInputStream fstream = new FileInputStream("textfile.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null)   {
    System.out.println (strLine);

Read the details at How to read file line by line in Java?

February 14, 2015 at 5:50 PM

The BufferedReader and the BufferedReader classes are developed to read from the input stream.

The Scanner class provides more features such as parsing the tokens from the input stream while BufferedReader just reads the data from the input streams.

So, if you don't have any requirement of parsing the data while reading you simply use the BufferedReader class.

The BufferedReader class is used to read (just) read the data from the input streams much faster. In the case of reading the data one line at a time from the input stream just use the BufferedReader class.



Related Tutorials/Questions & Answers:
What is the fastest way to read a file in Java?
difference between java5 and java6 - Java Beginners
Javah -  Header File Generator
What is the best way to write to file in Java?
Javah - Header File Generator
Javah - Header File Generator
what fastest DataStructre(efficient) in java? and why? - Java Beginners
Fastest way to upload huge raw data in database - c#, Java or stored procedure
read a file
About Java2
about java1
What is dirty read?
Best way to reading file in java
file read
Read from file java
What is the best way to learn JavaScript?
What is the best way to learn JavaScript?
Read file in java
java read file
Read and write file
What is an efficient way to implement a singleton pattern in Java?
nio read file line by line
J2ME Read Multiple File - MobileApplications
fastest type of JDBC driver
Read external file in PHP
Java read binary file
Read Video File
What are some way to learn Java quickly?
Read the file Contents