Java 从String.split创建数组时出现NullPointerException
我正在读取一个文件,文件的每一行并不总是有相同数量的元素。某些行有2个元素,而其他行可能有4或6个元素。所以我要做的是根据线的分割方式创建一个临时数组。这里的问题是我得到了Java 从String.split创建数组时出现NullPointerException,java,arrays,file,Java,Arrays,File,我正在读取一个文件,文件的每一行并不总是有相同数量的元素。某些行有2个元素,而其他行可能有4或6个元素。所以我要做的是根据线的分割方式创建一个临时数组。这里的问题是我得到了String[]currentLine的java.lang.NullPointerException。但是程序仍然读取currentLine[1]的内容: boolean needData = true; String path = "foo/" + filename + ".bar";
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();
}
}
最终将返回null
,表示没有更多的输入可读取
返回:
包含行内容的字符串,不包括任何行终止字符,如果已到达流的结尾,则为null
但是,您已经设置了一个无限循环。您正在尝试处理一个不存在的行
检查
行
在while
循环的情况下是否为空
。这将在处理完最后一行后停止循环
while( (line = bufReader.readLine()) != null)
{
// Remove readLine call here
// The rest of the while loop body is the same
最终将返回null
,表示没有更多的输入可读取
返回:
包含行内容的字符串,不包括任何行终止字符,如果已到达流的结尾,则为null
但是,您已经设置了一个无限循环。您正在尝试处理一个不存在的行
检查
行
在while
循环的情况下是否为空
。这将在处理完最后一行后停止循环
while( (line = bufReader.readLine()) != null)
{
// Remove readLine call here
// The rest of the while loop body is the same
缓冲读卡器的
公共字符串readLine()
的文档说明:
包含行内容的字符串,不包括任何行终止字符,或null(如果已到达流的结尾)
因此,您只是到达了文件的末尾,因为您永远不会离开
,而缓冲读取器的公共字符串readLine()
的文档会说:
包含行内容的字符串,不包括任何行终止字符,或null(如果已到达流的结尾)
因此,您只是到达了文件的末尾,因为您永远不会离开,而您需要更改循环:
while((line = bufReader.readLine()) != null )
{
String[] currentLine = line.split(" "); // Error
String lineStartsWith = currentLine[0];
switch(lineStartsWith)
{
case "Name:" :
System.out.println(currentLine[1]);
break;
}
}
您需要更改循环:
while((line = bufReader.readLine()) != null )
{
String[] currentLine = line.split(" "); // Error
String lineStartsWith = currentLine[0];
switch(lineStartsWith)
{
case "Name:" :
System.out.println(currentLine[1]);
break;
}
}
如果line
为null
则很明显您将获得NPE。您应该在拆分行之前检查bufReader.readLine()的返回值。如果line
为null
则很明显您将获得NPE。您应该在拆分行之前检查bufReader.readLine()的返回值。