Java - 当我读取空文件时,如何避免NullPointerException

时间:2016-12-24 18:17:43

标签: java nullpointerexception

我有客户类和客户数组列表

我有一种从客户那里读取对象的方法。归档并将它们添加到数组列表

import java.util.*;
import java.io.*;

public void readFile(File customerFile) throws IOException, NullPointerException {
    ObjectInputStream OIS = null;

    try {
        FileInputStream FIS = new FileInputStream(customerFile);
        OIS = new ObjectInputStream(FIS);

        Customer customerObj = null;

        while (true) {
            customerObj = (Customer) OIS.readObject();
            this.customerList.add(customerObj);
        }
    } catch (Exception ex) {
        System.out.println("(Exception : " + ex.toString() + ")");
    } finally {
        OIS.close();
        if (!isEmpty()) {
            Print(); // print the customerList
        } else {
            System.out.println("The Customer List Is Empty !");
        }
    }
}

那么任何人都可以帮助我吗?

OIS.close();

处的NullPointerException

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码:

public void readFile(File customerFile) throws IOException, NullPointerException {
    try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(customerFile))) {
        Customer customerObj = null;

        while (true) {
            customerObj = (Customer) ois.readObject();
            this.customerList.add(customerObj);
        }
    } catch (Exception ex) {
        System.out.println("(Exception : " + ex.toString() + ")");
    }

    if (!isEmpty()) {
        Print(); // print the customerList
    } else {
        System.out.println("The Customer List Is Empty !");
    }
}

在我的代码中,我使用try-with-resources语句。它会自动关闭您的InputStream