0

How can I read in a txt file in Java?

So, I have a txt file with a varying number of lines, and I want to read in the txt file in an array of strings and have each line as one element of that array. This is what it looks like so far: In order to find the mistake, I wanted to program to print out something in a various number of places, so I know that the problem is that my program is stuck in an infinite while loop. How can I tell the program to store each line as a string but to stop trying to store things when there are no more lines in the document? Any help would be very much appreciated! :) import java.io.BufferedReader; import java.io.FileReader; public class Verteilen { public static void main(String[] args){ FileReader fr= new FileReader ("file.txt"); BufferedReader br= new BufferedReader (fr); try { int numLines = 0; //number of lines in txt file System.out.print(numLines);//just trying to find the mistake while (line != null) { ++numLines; System.out.print(numLines); } String[] text = new String[numLines]; for (int i=0; i<=numLines; i++) { text[i]=br.readLine(); } System.out.print(text[0]); //I just want to see if it works } finally { br.close(); System.out.print("file cannot be read"); } } }

19th Nov 2017, 2:29 PM
Gluehbirne
1 Answer
+ 2
The line where it says while (line != null), where is declaration of that variable named line, you did not declare it, hence the error.
19th Nov 2017, 3:43 PM
Ipang