使用BufferedReader取消引用可能的空指针

时间:2014-06-23 12:14:18

标签: java

我有这段代码:

...
BufferedReader reader= new BufferedReader(new FileReader(file));

while ((line = reader.readLine()) != null) {
      // Do stuff...
}
reader.close();

....

BufferedReader reader2= new BufferedReader(new FileReader(file));

while ((line = reader2.readLine()) != null) { // Here I get a "Dereferencing possible null pointer" warning!
      // Do stuff...
}
reader2.close();
...

如果我尝试执行它,我会在((line = reader2.readLine()) != null)得到一个NullPointerException。我不明白的是为什么reader2的声明正在返回null。这是否与我尝试在同一个文件上打开两个BufferedReaders的事实有关?

为什么会发生这种情况的任何想法?

编辑:完整代码:

    BufferedReader brFileToAdjust = new BufferedReader(new FileReader(fileToAdjust));
    String line;
    List<String> customersToAdjust = new ArrayList<String>();
    int lineNo = 0;

    while ((line = brFileToAdjust.readLine()) != null) {

        if (lineNo != 0) { // Do not do this for the first line.:
            String[] data = line.split("\t");
            if (!customersToAdjust.contains(data[0])) {
                customersToAdjust.add(data[0]);
            }
        }
        lineNo++;
    }

    brFileToAdjust.close();
    BufferedReader brFileToAdjust2 = new BufferedReader(new FileReader(fileToAdjust));

    for (String customer : customersToAdjust) {
        boolean newCustomer = true;
        String customerTransactions[][] = new String[999][6];
        String outputCustomerTransactions[][] = new String[999][15];
        lineNo = 0;
        int i = 0;
        while ((line = brFileToAdjust2.readLine()) != null) {
              ...
        }
    }
    brFileToAdjust2.close();

0 个答案:

没有答案