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(
at java.base/
at Tester.readArray(
at Tester.main(

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;
        String[]words = new String[wordCounter];
        Scanner s2 = new Scanner(new File(file));
        for (int i = 0; i < wordCounter; i = i + 1) {
            words[i] =;
        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.

Leave a Reply