0

I want to initialize String array with lines from .txt file. And I've written this:

    public static void main(String[] args) {

        File file = new File("file.txt");
        int linesNumber = 0;
        String str;

        try {
            Scanner fileScan = new Scanner(file);

            //counting lines number in the file
            while(fileScan.hasNextLine()) {
                fileScan.nextLine();
                linesNumber++;
            }

            String[] strArray = new String[linesNumber];
            fileScan.reset();

            //assigning the array with lines from .txt file
            for (int i = 0; i < linesNumber; i++) {
                if (fileScan.hasNextLine()) {
                    strArray[i] = fileScan.nextLine();
                }
            }

            for (String s : strArray) {
                System.out.println(s);
            }

        } catch (FileNotFoundException ex) {
            System.out.println("Blad");
        }
    }

When I try to read the array in the last for loop, it gives me 20 lines of 'null'. Why is that? The .txt file is just 20 single words, each one in another line.

  • 3
    Basically, `Scanner.reset` doesn't do what you think it should. (It's a pretty poorly designed API in my opinion.) The simple solution is to create an `ArrayList` instead, so you only need to read through the file once. Or simpler, use `Files.readAllLines` – Jon Skeet Jun 10 '20 at 11:15
  • 1
    `Scanner.reset()` doesn't do what you think it does. Please read `Scanner`'s documentation. Not sure why you want to count the lines before you read. But in any case, wouldn't it be better to use `Files.readAllLines()` (read `Files`'s documentation as well). – RealSkeptic Jun 10 '20 at 11:16
  • Does this answer your question? [Resetting a .nextLine() Scanner](https://stackoverflow.com/questions/13991494/resetting-a-nextline-scanner) – Norbert Dopjera Jun 10 '20 at 11:17
  • Have you checked the .txt file for any blank lines after 20 words. – Ankit Jun 10 '20 at 11:18

2 Answers2

1

This is kind a duplicate of Resetting a .nextLine() Scanner

fileScan.reset();

doesn't do what you think it does. Please read documentation here: https://www.geeksforgeeks.org/scanner-reset-method-in-java-with-examples/

Norbert Dopjera
  • 741
  • 5
  • 18
0

Did you try it with fileScan.close() ?

Scanner fileScan = new Scanner(file);

//counting lines number in the file
while(fileScan.hasNextLine()) {
     fileScan.nextLine();
     linesNumber++;
}
fileScan.close();
Icomar
  • 11
  • 2