[英]BufferedWriter not writing the array
我使用了缓冲编写器将数组中的内容写入文本文件
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();
}
customer[]
数组如下:
String customer[] = new String[10];
customer[1]="Anne";
customer[2]="Michelle";
但是,当我尝试写入文件时,出现以下错误:
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)
我发现错误是由于customer[0]
为null引起的。 我想避免使用null元素,而只编写具有字符串内容的元素。 有没有办法处理此错误?
几件事。 首先,数组索引从0开始,而不是1。您应该从customer[0]
。
customer[0] = "Anne";
customer[1] = "Michelle";
其次,您可以检查是否为空。 那是一种方式。
for (String line: customer) {
if (line != null) {
bw.write(line);
bw.newLine();
}
}
更好的方法是使用ArrayList
而不是原始数组。 数组是固定大小的集合。 如果您想拥有数量可变的元素,则ArrayList
将更适合您。 您不必提防null元素。 如果添加两个客户,该列表将有两个条目,而不是十个。
List<String> customers = new ArrayList<>();
customers.add("Anne");
customers.add("Michelle");
for (String customer: customers) {
bw.write(customer);
bw.newLine();
}
(顺便说一句,我鼓励您使用上面的命名方案。常规变量是单数形式,而数组和列表使用复数形式: customers
是一个列表,而每个元素都是一个customer
。)
默认情况下,对象数组(如字符串)用null
值填充。 所以用
String customer[] = new String[10];
customer[1]="Anne";
customer[2]="Michelle";
您将以[null, "Anne", "Michelle", null, null, ..., null]
这样的数组结尾。
现在, write
方法的代码如下所示:
public void write(String str) throws IOException {
write(str, 0, str.length());
}
因此,当您传递null
(默认情况下,字符串数组填充为null
), str.length()
最终会成为null.length()
,这是无效的,因为null
没有任何方法或字段,并且会引发NPE。
如果您想跳过null
元素,则可以使用==
或!=
对其进行测试,例如
for (String line : customer) {
if (line != null){
bw.write(line);
bw.newLine();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.