当我使用缓冲读取器时出现NullPointerException异常

问题描述 投票:-1回答:1

我有这样一段代码,它读取一个文件,并创建一个字符串数组列表,并将其转换为行和列的列表,这段代码运行良好,但我不知道为什么会出现NullPointerException。这段代码运行良好,但我不知道为什么会抛出NullPointerException。你能帮助我吗?

private List<String[]> csvToList(String inputFile, String delimiter) {
		
		String line[];
		
		List<String[]> lines = new ArrayList<String[]>();
			
		try (BufferedReader br = new BufferedReader(new FileReader(inputFile))){
			
			// Gets the first row of the input (Header)
			line = br.readLine().split(delimiter);
			
			if (line.length > 0) lines.add(line);			
			
			while (line.length > 0) {
				line = br.readLine().split(",");	
				
				if (line.length > 0) lines.add(line);		
			}
			
			br.close();
			
		} catch(NullPointerException npe) {
			// Here is thrown a null pointer exception
		} catch(Exception ex) {
			ex.printStackTrace();
		}
		
		
		return lines;
	}
java nullpointerexception
1个回答
0
投票

在你的情况下,NPE意味着你到达了文件的末端--你需要检查是否有 null 呼叫 br.readLine():

String singleLine;
while((singleLine = br.readLine()) != null) {
    line = singleLine.split(",");
    if (line.length > 0) {
        lines.add(line);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.