- 9 days ago 4
Java Question

Why am I unable to add lines from a text file to an ArrayList in Java?

I have the following code below. If I comment out the

I can get it to print the lines of the document (5 lines of text with spaces). If I don't comment it out, I get one line printed and the null. I have looked up everything I could online but I am not understanding why this is happening!

package examples.files;

import java.util.ArrayList;
import java.util.Scanner;

* @author
public class ReadFileUsingScanner {
static ArrayList<String> stringList = null;
* @param args
* @throws Exception
public static void main(String[] args) {
Scanner scanner = null;

try {
scanner = new Scanner(new File("customers.txt"));

while (scanner.hasNext()) {
String row = scanner.nextLine();
} catch(Exception e) {
} finally {
if (scanner != null) {
try {
} catch (Exception e) {}


You don't have to solve the code but I want to understand the fundamentals as to why it doesn't work.


Your arrayList is not initialized. Change to

static ArrayList<String> stringList = new ArrayList<String>();