我正在读取一个文件,文件的每一行并不总是具有相同数量的元素。有些行有 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/