Java 使用 BufferedReader (readLine()) 检查更多值时如何停止 NullPointerException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21101358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:35:35  来源:igfitidea点击:

How to stop a NullPointerException when using BufferedReader (readLine()) to check for any more values

javaobjectiobufferedreaderfileinputstream

提问by

I have written some code to read in Vehicle data from a .txt file. At the moment I can read in all the data correctly and create the objects fine. I have a while loop that checks for the text "Vehicle Details" in the file and if it is present (i.e. there is another vehicle to add) it enters the loop to add the data.

我已经编写了一些代码来从 .txt 文件中读取车辆数据。目前我可以正确读取所有数据并创建对象。我有一个 while 循环来检查文件中的文本“车辆详细信息”,如果它存在(即有另一辆车要添加),它就会进入循环以添加数据。

The problem is that when there isn't anymore data the readLine() method is still called and this creates a NullPointerException (at least that's what I think is the cause)

问题是,当不再有数据时,仍会调用 readLine() 方法,这会创建一个 NullPointerException(至少我认为这是原因)

Here is the method in use.

这里是使用的方法。

public static void addNewVehicleFromFile(Showroom s)
{
    try
    {
        FileInputStream fStream = new FileInputStream("AddVehicleFromFile.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(fStream));
        String stringLine;

        while ((stringLine = br.readLine()).equalsIgnoreCase("Vehicle Details"))
        {
            System.out.println("P1");//Testing
            br.readLine();

            String[] manufacturer = br.readLine().split(" =");
            String[] model = br.readLine().split(" =");
            String[] vin = br.readLine().split(" =");
            String[] dateOfMan = br.readLine().split(" =");
            String[] taxBand = br.readLine().split(" =");
            String[] cost = br.readLine().split(" =");

            System.out.println("P2");//Testing
            System.out.println(manufacturer[0].toString());
            System.out.println(model[0].toString());
            System.out.println(vin[0].toString());
            System.out.println(dateOfMan[0].toString());
            System.out.println(taxBand[0].toString());

            br.readLine();

            System.out.println("P3");//Testing

            int strToInt = Integer.parseInt(cost[0]);

            Vehicle inputVehicle = new Vehicle(manufacturer[0], model[0], vin[0], dateOfMan[0],
                    taxBand[0].charAt(0), strToInt);

            System.out.println("P4");//Testing

            s.addVehicle(inputVehicle);

            System.out.println("P5");//Testing
        }

    }
    catch (FileNotFoundException fnfe)
    {
        System.out.println("File not found exception: " + fnfe.toString());
    }
    catch (IOException ioe)
    {
        System.out.println("I/O exception: " + ioe.toString());
    }

    System.out.println("addNewVehicleFromFile Complete");

}

Not sure if you need it but here is my file data.

不确定您是否需要它,但这是我的文件数据。

Vehicle Details

Fordtest =manufacturer
Focus =model
ioCheck =VIN
09/01/1989 =DateOfMan
d =TaxBand
19900 =Cost

Vehicle Details

Fordtest2 =manufacturer
Focus2 =model
ioCheckVIN2 =VIN
09/01/1989 =DateOfMan
a =TaxBand
1922 =Cost

Finally, to make it clear where the program runs to I have added in some console output as testing. The while loops iterates twice outputting p1-p5 both times before the error occurs and it never reaches the final console output saying the method is complete.

最后,为了明确程序运行的位置,我添加了一些控制台输出作为测试。while 循环在错误发生之前两次迭代输出 p1-p5 并且它永远不会到达最终的控制台输出,表明该方法已完成。

采纳答案by Drifter64

Check that the result of calling readLine() is not null (empty). If you check, and cause it not to do anything if its empty, this will solve your issue!

检查调用 readLine() 的结果是否为空(空)。如果您检查,并在它为空时使其不执行任何操作,这将解决您的问题!

回答by Ian Schmitz

Try checking if readLine() is null. while ((stringLine = br.readLine()) != null) { }This will make sure that there is something in that line to read, else it has reached end of file.

尝试检查 readLine() 是否为空。 while ((stringLine = br.readLine()) != null) { }这将确保该行中有内容要读取,否则它已到达文件末尾。

In your code you have 3 calls to readLine() each iteration. This could cause issues if for some reason the formatting in your text file is changed(missing a blank line for example). You may be better off making each vehicle on one line, seperated by commas. For example:

在您的代码中,每次迭代都会调用 3 次 readLine()。如果由于某种原因更改了文本文件中的格式(例如缺少空行),这可能会导致问题。您最好将每辆车放在一行上,用逗号分隔。例如:

Vehicle Details

Fordtest =manufacturer
Focus =model
ioCheck =VIN
09/01/1989 =DateOfMan
d =TaxBand
19900 =Cost

Vehicle Details

Fordtest2 =manufacturer
Focus2 =model
ioCheckVIN2 =VIN
09/01/1989 =DateOfMan
a =TaxBand
1922 =Cost

Then becomes:

然后变成:

Fordtest, Focus, ioCheck, 09/01/1989, d, 19900
Fordtest2, Focus2, ioCheckVIN2, 09/01/1989, a, 1922

This would simplify the code somewhat, as well as reducing chance for error.

这将在一定程度上简化代码,并减少出错的机会。

Also make sure to close the FileInputStream when you are finished with it. This insures that any resources associated with it are released properly.

还要确保在完成 FileInputStream 后关闭它。这确保了与之相关的任何资源都被正确释放。

try {
    FileInputStream fStream = new FileInputStream("AddVehicleFromFile.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(fStream));
    ...
} finally {
    try {
        if (fStream != null) {
            fStream.close();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}