synthesize.me synthesize.me - 1 month ago 5
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

stringList.add(row);
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.io.File;
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();
System.out.println(row);
stringList.add(row);
}
} catch(Exception e) {
System.out.println(e.getMessage());
} finally {
if (scanner != null) {
try {
scanner.close();
} 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.

Answer

Your arrayList is not initialized. Change to

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