简体   繁体   中英

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);
}

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
}

I just experienced this very problem. It seems that it works just by changing the scanner construction. Replace this:

File file1 = new File("file1");
Scanner in= new Scanner(file1);

with this:

FileReader file1 = new FileReader("file1");
Scanner in= new Scanner(file1);

Maybe the problem appears when you build your scanner from a file without the system knowing that it is a text file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM