BufferedWriter没有写数组

时间:2016-08-13 20:31:29

标签: java arrays bufferedwriter

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

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元素,只编写具有字符串内容的元素。有没有办法处理这个错误?

2 个答案:

答案 0 :(得分:2)

一些事情。首先,数组索引从0开始,而不是1.你应该从customer[0]开始。

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

其次,您可以检查null。这是单向的。

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是一个列表,每个元素都是{{1} }。)

答案 1 :(得分:1)

默认情况下,对象数组(如字符串)填充 Something something1 = applicationContext.getBean(Something.class); Something something2 = applicationContext.getBean(Something.class); Assert.assertEquals(something1, something1); Assert.assertNotEquals(something1, something2); something1.doWhatever(); something2.doWhatever(); 个值。所以用

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 s)null最终为str.length(),自null.length()起无效没有任何方法也没有字段和NPE被抛出。

如果您想跳过null元素,只需使用null==

进行测试即可
!=
相关问题