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
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?
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