Scanner reading large file

 ̄綄美尐妖づ 提交于 2019-12-17 20:09:27

问题


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

回答1:


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
}



回答2:


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.



来源:https://stackoverflow.com/questions/19813760/scanner-reading-large-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!