我很难在第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");
     }


    }
}


提前致谢!

最佳答案

几乎可以肯定,您会误读触发错误的行。

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
  }
}

关于java - 在while循环中使用bufferedReader时获取NullPointerException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23349581/

10-11 22:31
查看更多