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

Ads
 

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

Hi,

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) 
    {

        try{
          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.

Thanks

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.

Thanks

Ads









Related Tutorials/Questions & Answers:
What is the fastest way to read a file in Java?
What is the fastest way to learn AI?
Advertisements
What is the best way to write to file in Java?
Javah -  Header File Generator
What is the fastest growing careers?
Javah
Java2
Javah - Header File Generator
read a file
Best way to reading file in java
Fastest way to upload huge raw data in database - c#, Java or stored procedure
file read
Read from file java
Read file in java
java read file
nio read file line by line
Read and write file
What is the best way to learn Bootstrap?
What is the best way to learn Bootstrap?
Read external file in PHP
What is the best way to learn JavaScript?
What is the best way to learn JavaScript?
What is the best way to learn java
What is the best way to learn JavaScript?
Java read binary file
How to read a file line by line?
What is an efficient way to implement a singleton pattern in Java?
Read the file Contents
Steps to read text file in pyspark
read doc and docx file in javascript
Read text File

Ads