0

I am writing code that first) asks the user for a file name second) reads the file and puts each line into an ArrayList third) prints out the ArrayList

My code is reading the file with a BufferedReader, but it is only printing out the first line 25 times instead of printing out the 25 different lines.

This is what my while loop looks like. I don't know how to increment it though

ArrayList<String> stringArray = new ArrayList<String>();
BufferedReader reader = null;
reader = new BufferedReader(new FileReader(fileName));

String line = reader.readLine();
while(reader.readLine() != null){
    stringArray.add(line);
}
return stringArray;

Any thoughts?

Victory
  • 5,811
  • 2
  • 26
  • 45
lovethehelp
  • 125
  • 6
  • 13
  • For a simpler solution using `Scanner`, (or even a one-liner using Apache Commons I/O or Google Guava), see [Java reading a file into an ArrayList?](http://stackoverflow.com/questions/5343689/java-reading-a-file-into-an-arraylist) – Mick Mnemonic Oct 21 '15 at 23:33

3 Answers3

2

You are not reading in the line to the variable on each run, you need to read it in the while loop.

String line = reader.readLine();
while(line != null){
    stringArray.add(line);
    line = reader.readLine(); // read the next line
}
return stringArray;
Victory
  • 5,811
  • 2
  • 26
  • 45
0

This is not the preferred solution. Just showing that it can be done a different way

Or you can use a do...while instead of while...do.

String line;
do {
    line = reader.readLine();
    if (line != null) {
       stringArray.add(line);
    }
} while (line != null);

You can see why this isn't the preferred solution. You are doing 2 null checks where you can get away with 1.

Sammy
  • 467
  • 3
  • 13
  • Why post "not the preferred solution"? – javabrew Oct 22 '15 at 01:00
  • For the same reason we study sorting algorithms other than Quicksort, Mergesort and Heapsort. Sometimes seeing a different way of doing things improves our understanding and appreciation. Sometimes it provides background. Sometimes a different construct can prove useful in a different circumstance. Why is there a do while loop in Java when a while loop can do exactly the same thing with just one extra flag? – Sammy Oct 22 '15 at 02:29
  • Sorry but i didn't present it as a "good" piece of code. And I described exactly why it isn't preferred. And by the way many programmers consider using break as per your solution to be bad coding too. – Sammy Oct 22 '15 at 02:43
0
 while (true) {
    String line = reader.readLine(); 
    if (line == null) break;
    stringArray.add(line);
 }
 return stringArray;
javabrew
  • 306
  • 4
  • 7