Dindi Rave Dindi Rave - 3 months ago 11
Java Question

BufferedWriter not writing the array

I have used a buffered writer to write the contents in an array to a text file

try {
File file = new File("Details.txt");

if (!file.exists()) {
file.createNewFile();
}

FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);


for (String line : customer) {
bw.write(line); //line 178
bw.newLine();
}

bw.flush();
bw.close();

System.out.println("Done");

} catch (IOException e) {
e.printStackTrace();
}


The
customer[]
array is as follows:

String customer[] = new String[10];
customer[1]="Anne";
customer[2]="Michelle";


But when I try writing to the file I get the following error:

Exception in thread "main" java.lang.NullPointerException
at java.io.Writer.write(Unknown Source)
at HotelFunctions.storeData(CustomerMenu.java:178)
at MainClass.main(MainClass.java:38)


I found out that the error is caused because
customer[0]
is null. I want to avoid the null elements and only write the elements that have string content. Is there a way to handle this error?

Answer

A couple things. First, array indices start at 0, not 1. You should start at customer[0].

customer[0] = "Anne";
customer[1] = "Michelle";

Second, you could check for null. That's one way.

for (String line: customer) {
    if (line != null) {
        bw.write(line);
        bw.newLine();
    }
}

A better way is to use an ArrayList instead of a raw array. Arrays are fixed size collections. If you want to have a varying number of elements an ArrayList will suit you better. You won't have to guard against null elements. If you add two customers, the list will have two entries, not ten.

List<String> customers = new ArrayList<>();

customers.add("Anne");
customers.add("Michelle");

for (String customer: customers) {
    bw.write(customer);
    bw.newLine();
}

(By the way, I encourage you to use the naming scheme I did above. Regular variables are singular while arrays and lists use the plural: customers is a list, and each element is a customer.)

Comments