gpt4 book ai didi

java - BufferedWriter 不写入数组

转载 作者:行者123 更新时间:2023-12-01 21:22:12 26 4
gpt4 key购买 nike

我使用缓冲写入器将数组中的内容写入文本文件

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引起的。我想避免空元素,只写入具有字符串内容的元素。有没有办法处理这个错误?

最佳答案

有几件事。首先,数组索引从 0 开始,而不是 1。您应该从 customer[0] 开始。

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

其次,您可以检查是否为空。这是一种方法。

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

更好的方法是使用 ArrayList 而不是原始数组。数组是固定大小的集合。如果您想要不同数量的元素,ArrayList 会更适合您。您不必防范空元素。如果您添加两个客户,列表将有两个条目,而不是十个。

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

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

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

(顺便说一句,我鼓励您使用我上面所做的命名方案。常规变量是单数,而数组和列表使用复数:customers 是一个列表,每个元素都是一个 客户。)

关于java - BufferedWriter 不写入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38936742/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com