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

Spi*_*nie 0 java arrays file

我正在读取文件,文件的每一行并不总是具有相同数量的元素.一些行有2个元素,而其他行可能有4或6个元素.所以我正在做的是根据线的分割方式创建一个临时数组.这里的问题是我得到一个java.lang.NullPointerException String[] currentLine.但该程序仍然读取以下内容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();
            }
        }
Run Code Online (Sandbox Code Playgroud)

rge*_*man 5

BufferedReaderreadLine方法最终将返回null,表明没有更多的输入要读取.

返回:

包含行内容的String,不包括任何行终止字符;如果已到达流的末尾,则为null

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

检查linenull在条件while循环.一旦最后一行已被处理,这将停止循环.

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