Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to read a big file of 500,000 lines and store it in an array in java

which checks the performance of different sorting algorithms. We were given a .txt file with 500,000 words, which are going to be sorted with these algorithms. I wrote the method that reads the file and stores the words in a String array. The first Scanner counts the number of lines and the second Scanner creates the array using the counter but it only works with files with much less lines. Ican’t really share the content of the text file, it is just a file containing 1 word in each line.

When I try to read the file with the 500,000 lines I get this:

Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at Tester.readArray(Tester.java:81)
at Tester.main(Tester.java:7)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Do you think it is because my computer does not support it, or do I need to change the method?
Here is my method:

public static String[] readArray(String file) {
    int wordCounter = 0;
    try {
        Scanner s1 = new Scanner(new File(file));
        while (s1.hasNextLine()) {
            wordCounter = wordCounter + 1;
            s1.next();
        }
        s1.close();
        String[]words = new String[wordCounter];
        Scanner s2 = new Scanner(new File(file));
        for (int i = 0; i < wordCounter; i = i + 1) {
            words[i] = s2.next();
        }
        return words;
    }
    catch (FileNotFoundException e) {
    
    }
    return null;
}

>Solution :

So for me replacing hasNextLine() with hasNext() fixed the exception. This has nothing to do with your PC.
I think this error can occur, when you have an empty line at the end of your file. Because, when I removed my empty line at the end of the file i was reading the exception was not thrown.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading