Reputation: 23
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?
Upvotes: 0
Views: 365
Reputation: 361655
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
.)
Upvotes: 2
Reputation: 124235
By default array of objects (like Strings) are filled with null
values. So with
String customer[] = new String[10];
customer[1]="Anne";
customer[2]="Michelle";
you are ending with array like [null, "Anne", "Michelle", null, null, ..., null]
.
Now, code of write
method looks like:
public void write(String str) throws IOException {
write(str, 0, str.length());
}
so when you are passing null
(String array is by default filled with null
s) str.length()
ends up as null.length()
which is invalid since null
doesn't have any methods nor fields and NPE is thrown.
If you want to skip null
elements you can simply test them with ==
or !=
like
for (String line : customer) {
if (line != null){
bw.write(line);
bw.newLine();
}
}
Upvotes: 1