I have a text file containing 5 customers (1 per line), Customer 1, Customer 2, Customer 3, Customer 4 and Customer 5. Using the following code, it reads the 5 lines of text perfectly;
import java.io.*;
public class CustomerIO {
public void method () {
try (BufferedReader br = new BufferedReader(new FileReader(new File ("Customers.txt")))) {
int numberOfLines = readLines();
String [] text = new String [numberOfLines];
for (int i = 0; i < numberOfLines; i++) {
text[i] = br.readLine();
}
for (int i = 0; i < numberOfLines; i++) {
System.out.println(text[i]);
}
} catch (Exception e) {
e.printStackTrace();
}
private int readLines() {
try (BufferedReader br = new BufferedReader(new FileReader(new File ("Customers.txt")))) {
while ((line = br.readLine()) != null) {
numberOfLines++;
}
} catch (Exception e) {
e.printStackTrace();
}
return numberOfLines;
}
}
However when I change to the following the output is: Customer 2, Customer 4, null
import java.io.*;
public class CustomerIO {
String line;
int numberOfLines = 0;
public void method () {
try (BufferedReader br = new BufferedReader(new FileReader(new File ("Customers.txt")))) {
while (br.readLine() != null) {
System.out.println(br.readLine());
}
} catch (Exception e) {
e.printStackTrace();
}
}
private int readLines() {
try (BufferedReader br = new BufferedReader(new FileReader(new File ("Customers.txt")))) {
while ((line = br.readLine()) != null) {
numberOfLines++;
}
} catch (Exception e) {
e.printStackTrace();
}
return numberOfLines;
}
}
The main method is contained in the following runner.class file
public class Runner {
public static void main(String[] args) {
CustomerIO cus = new CustomerIO ();
cus.method();
}
}
Can you help me understand why this is happening? I want to read the customers into an arraylist when its reading in correctly rather than working with a String [].
Thanks