Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在while循环中使用bufferedreader时获取NullPointerException_Java_Nullpointerexception - Fatal编程技术网

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

Java 在while循环中使用bufferedreader时获取NullPointerException,java,nullpointerexception,Java,Nullpointerexception,我在第71行很难找到一个错误。我需要从一个文本文件中读取数据,将数据收集到一些树形图中,以便稍后在两个输出文件中对其进行修改。我有一个while循环,通过将文本置于大写来修改数据,然后我将数据拆分为每行的一个数组,然后将该数组数据置于3个树映射中。这个错误是一个NullPointerException,当我注释掉这行时,它会将它抛出到另一行,所以很明显我的循环总体上有问题,我就是看不到。循环似乎比遍历所有行少运行一次,因此如果文本文件有5行,它将读取4行,给我正确的值,然后抛出错误。我试图修改文

我在第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
   Scanner scanner = new Scanner(new File(listInput));
   while (scanner.hasNext()) {
      String line = scanner.next();
      //do the rest of your stuff
   }
   scanner.close();
以下是错误代码:

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");
     }


    } 
}

提前谢谢

您正在调用
line=br.readLine()在循环中,然后不检查它是否为null

例如,如果您有一行,您将得到
NullPointerException

请遵循Dima Goltsman的建议,或者像这样使用Scanner类:

110001 commercial 500000.00 101

110223 residential 100000.00 104

110020 commercial 1000000.00 107

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

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

当您使用
br.readLine()时null
。所以你需要在条件检查前使用它

p、 美国


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

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

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
。相反,请执行以下操作(同时注意语法):


我会的,但我需要使用BufferedReader。我真的很感谢你的帮助@用户3576714好的,没问题,非常感谢!是的,这一行。toUpperCase抛出了异常,但是当我注释掉它时,它只会在下一行抛出异常,所以我认为这不是真正的问题。谢谢你的帮助!一点一点地学习。