在while循环中使用bufferedreader时获取NullPointerException

时间:2014-04-28 19:27:42

标签: java nullpointerexception

我很难确定我在第71行上的错误。我需要从文本文件中读取数据,将数据收集到一些树形图中,以便稍后在两个输出文件中对其进行修改。我有一个while循环,它通过将文本放在大写中来修改数据,然后我将数据拆分成每行的数组,然后将该数组数据放在3个树图中。错误是一个NullPointerException,当我注释掉它的行时,它会将它抛出到另一行,所以我的循环显然有问题,我只是看不到它。循环似乎运行了一段时间没有通过所有行,所以如果文本文件有5行,它将读取4,给我正确的值,然后抛出错误。我试过修改文本文件的内容,但没有用。我试过修改while循环,也没用。任何指针都将非常感激。文本文件如下所示:

110001 commercial 500000.00 101

110223 residential 100000.00 104

110020 commercial 1000000.00 107

550020 land 400000.00 105

这是错误代码:

java.lang.NullPointerException
    at realestate.RealEstate.main(RealEstate.java:71)

到目前为止,这是我的代码:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package realestate;

import java.io.BufferedReader;
import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import static java.lang.System.out;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * 
 */
public class RealEstate {
    /**
     * @param args the command line arguments
     * @throws java.io.IOException
     */
    public static void main(String[] args) throws IOException {

        Scanner input = new Scanner(System.in);//Prompt user for listings.txt location.
        String listInput = null;
        System.out.print("Please enter the real estate listings.txt file's full path: ");
        listInput = input.next();
        if(listInput.contains("listings.txt") == false) {//Verify input with if else statement.
          System.out.print("\nSorry, the path entered will not work. Please enter the full path to listings.txt: ");
          listInput = input.next();
            if(listInput.contains("listings.txt") == true){//Nested in order to display same message.
                System.out.print("\nThank you, the agentreport.txt file is now available.");
          }
        } else {
            System.out.print("\nThank you, the agentreport.txt file is now available.\n");
        }
    String[][] listArray;  //Initialize array for later data manipulation.
    listArray = new String[10][5];
    listArray = null;
     Path ar = Paths.get("D:\\JAVA\\RealEstate\\agentreport.txt");//Deletes agentreport.txt if it already exists.
     try {
         Files.deleteIfExists(ar);
     } catch (IOException x) {
         System.out.print("\nIO Exception, please try again.");
     }

     //Reads listings.txt, parses information, places data in array, then inside treemaps.
     BufferedReader br = null;
     String[] lineArray = new String[4];
     TreeMap tm1 = new TreeMap();
     TreeMap tm2 = new TreeMap();
     TreeMap tm3 = new TreeMap();
     try {
         br = new BufferedReader(new FileReader(listInput));
            String line = br.readLine();
         while(line != null){//WHERE I"M GETTING ERROR
             line = br.readLine();//Read line.
             line = line.toUpperCase();//Make everything uppercase.
             lineArray = line.split("\\s+");//Place line into new array based on where spaces are.
             tm1.put(lineArray[0], lineArray[1]);//Place array items into treemaps.
             tm2.put(lineArray[0], lineArray[2]);
             tm3.put(lineArray[0], lineArray[3]);
             System.out.print(tm1 + "\n" + tm2 + "\n" + tm3 + "\n");//Test if data is received correctly.
             lineArray = null;//Clear array for next line.
         }
     } catch (NullPointerException e) {
         e.printStackTrace();
     } catch (IOException e) {
         e.printStackTrace();
         System.out.print("\nIO Exception, please try again.");
     }

     try {//File writer, creates file agentreport.txt and starts writing.
       File arFile = new File("D:\\JAVA\\RealEstate\\agentreport.txt");
       FileOutputStream is = new FileOutputStream(arFile);
       OutputStreamWriter osw = new OutputStreamWriter(is);
       Writer w = new BufferedWriter(osw);
       //w.write();//what I need the writer to do
       //w.close();
     } catch (FileNotFoundException e) {
         System.err.println("Problem writing to the file, agentreport.txt");
     }


    } 
}

提前致谢!

3 个答案:

答案 0 :(得分:2)

更改

 br = new BufferedReader(new FileReader(listInput));
        String line = br.readLine();
     while(line != null){//WHERE I"M GETTING ERROR

 br = new BufferedReader(new FileReader(listInput));
        String line = null;
     while((line=br.readLine()) != null){//WHERE I"M GETTING ERROR

在循环中使用br.readLine();时,它仍然可以获得null。所以你需要在条件检查之前使用它

P.S。

在代码中

,跳过第一行。我的代码也会解决这个问题

答案 1 :(得分:0)

你在循环中调用line = br.readLine();,然后不检查它是否为空。

例如,如果您有1行,您将获得NullPointerException

要么遵循Dima Goltsman的建议,要么像这样使用Scanner类:

   Scanner scanner = new Scanner(new File(listInput));
   while (scanner.hasNext()) {
      String line = scanner.next();
      //do the rest of your stuff
   }
   scanner.close();

答案 2 :(得分:0)

我几乎可以肯定你误读了引发错误的那一行。

String[] lineArray = new String[4]; // this is not needed, it gets overwritten
...
try {
  br = new BufferedReader(new FileReader(listInput));
  String line = br.readLine();
  while(line != null){
    line = br.readLine();
    line = line.toUpperCase(); // this will NPE
    ...
    lineArray = null; // you don't need this
  }
}

问题是,您在while循环中第二次调用readLine(),这意味着line现在可能是null。相反,这样做(注意try-with-resources语法):

try(BufferedReader br = new BufferedReader(new FileReader(listInput))) {
  String line = null;
  while((line=br.readLine()) != null){
    String[] lineArray = line.toUpperCase().split("\\s+");
    tm1.put(lineArray[0], lineArray[1]);//Place array items into treemaps.
    tm2.put(lineArray[0], lineArray[2]);
    tm3.put(lineArray[0], lineArray[3]);
    System.out.print(tm1 + "\n" + tm2 + "\n" + tm3 + "\n");//Test if data is received 
  }
}