Scanner isn’t picking up all the lines

Asked

Viewed 51 times

1

I have a file with 7 million lines, but my code takes at most 63000 and returns no 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++;
    }
  • The tips below did not serve?

  • Sorry, at the time I went to give the answer as sure still had to wait 7 minutes and I forgot, thanks for reminding me :D

  • If you can implement your answer by telling the difference between FileReader and File, can help others in the future :D

  • Ready, added :)

1 answer

3


I believe it may be due to memory usage limitations of the class File, try the form 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 don’t want to change the whole implementation, try switching File for 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 from files, ie, File does not represent a file, and yes, its path only, while FileReader is the representation of the data(characters) of this file.

References:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.