java - 从 String.split 创建数组时出现 NullPointerException

标签 java arrays file

我正在读取一个文件,文件的每一行并不总是具有相同数量的元素。有些行有 2 个元素,而其他行可能有 4 或 6 个元素。所以我正在做的是根据线路的分割方式创建一个临时数组。这里的问题是我得到了 String[] currentLine 的 java.lang.NullPointerException 。但程序仍然读取currentLine[1]的内容:

        boolean needData = true;    
        String path = "foo/" + filename + ".bar";
        File dataFile = null;
        BufferedReader bufReader = null;
        String line = null;

        if (needData) // always true
        {
            try
            {
                dataFile = new File(path);
                FileReader fr = new FileReader(dataFile);
                bufReader = new BufferedReader(fr);

                if (file.exists())
                {
                    while(true)
                    {
                        line = bufReader.readLine();
                        String[] currentLine = line.split(" "); // Error
                        String lineStartsWith = currentLine[0];

                        switch(lineStartsWith)
                        {
                          case "Name:" :
                              System.out.println(currentLine[1]);
                          break;
                        }
                    } // end while loop
                }
                bufReader.close();
            }
            catch (FileNotFoundException e)
            {
                System.err.println("Couldn't load " + filename + ".bar");
                e.printStackTrace();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }

最佳答案

BufferedReader's readLine method最终会返回null,表示没有更多的输入可以读取。

Returns:

A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

但是,您设置了无限循环。您正在尝试处理不存在的行。

检查while循环条件中line是否为null。一旦处理完最后一行,这将停止循环。

while( (line = bufReader.readLine()) != null)
{
    // Remove readLine call here
    // The rest of the while loop body is the same

关于java - 从 String.split 创建数组时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30581290/

相关文章:

java - 梯度下降的theta值是什么意思?

c++ - 将 `const` CV 限定符应用于衰减数组样式 `T arr[]` 函数参数(旨在衰减到 `T * const arr` )

javascript - 在javascript中搜索和删除数组元素

python - 在 python 中使用 file.seek() 时通常将多少字节加载到内存中?

php - 扩展文件系统

c - 多线程和读取文件

java - 如何启用/禁用java,eclipse中的按钮?

java - 如何在没有堆错误的情况下将大型 java 对象编码为 xml?

python - python/numpy中的线性组合

java - 无法创建谷歌地图 fragment