Scanner is not picking up all lines

2

I have a file with 7 million lines, but my code takes a maximum of 63000 and does not return any error.

Scanner sc2 = null;
    try {
        sc2 = new Scanner(new File("./assets/words.txt"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();  
    }

    int cont = 0;

    while(sc2.hasNextLine()) {
        String s = sc2.next();
        System.out.println(s + " - " + cont);
        cont++;
    }
    
asked by anonymous 27.07.2017 / 20:06

1 answer

3

I believe this might be due to memory usage limitations of the File class, try as below, suggested in a similar question in SOEn :

BufferedReader br = new BufferedReader(new FileReader(filepath));
String line = "";
while((line=br.readLine())!=null)
{
    // do something
}

Or if you do not want to change the entire implementation, try switching File to FileReader :

Scanner sc2 = null;
    try {
        sc2 = new Scanner(new FileReader("./assets/words.txt"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();  
    }

    int cont = 0;

    while(sc2.hasNextLine()) {
        String s = sc2.next();
        System.out.println(s + " - " + cont);
        cont++;
    }

The difference between File and FileReader " is that the first is just an abstract representation of the file, the second is the class for reading characters of files, that is, File does not represent a file, but, its path only, while FileReader is the representation of the data (characters) of this file.

References:

27.07.2017 / 20:11