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.