Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scanner reading large file

I am playing around with the Scanner class for learning purposes and i use it to read a very large file (60.000 lines aprox) without using the Reader class , and it stops reading after approximately 400 lines. Do i have to use a Bufferedreader inside the Scanner's constructor or the problem is something else? I want to know why this is happening. Thanks. My code is the usual code to output all the lines.

File file1 = new File("file1");
Scanner in= new Scanner(file1);
while  (scan.hasNextLine()  ) {
String str = scan.nextLine();
System.out.println(str);
}
like image 704
notArefill Avatar asked Nov 06 '13 13:11

notArefill


1 Answers

This issue is usually more common on 64 bit machines or with files having size more than 1-2 GB and does not have anything to do with heap space. Switch to BufferedReader it should work fine,

BufferedReader br = new BufferedReader(new FileReader(filepath));
String line = "";
while((line=br.readLine())!=null)
{
    // do something
}
like image 144
Ankit Rustagi Avatar answered Oct 04 '22 07:10

Ankit Rustagi