Java中使用BufferedReader读取TXT时字符串为null、数值为0的问题求助
问题分析与解决
你的代码核心问题是只统计了文件行数,完全没解析每行的内容,直接创建空的ListClasses对象加入集合,所以对象里的字符串字段默认是null,double字段默认是0.0。另外还有资源关闭的错误:你声明了br但没赋值,实际用的是breader,finally里关闭br等于没关,还会触发空指针(虽然你catch了,但没必要)。
修正步骤
1. 明确文件格式
首先得确定你的文本文件每行的数据格式,比如假设每行是用逗号分隔的字符串和数值,示例格式:
苹果,3.5 香蕉,2.8 橙子,4.2
2. 确保ListClasses有字段初始化方式
ListClasses需要有对应的字段和构造方法/setter,示例:
public class ListClasses { private String itemName; private double itemPrice; // 构造方法 public ListClasses(String itemName, double itemPrice) { this.itemName = itemName; this.itemPrice = itemPrice; } // 或提供setter方法 public void setItemName(String itemName) { this.itemName = itemName; } public void setItemPrice(double itemPrice) { this.itemPrice = itemPrice; } }
3. 修正读取解析代码
用try-with-resources自动关闭流,同时解析每行数据:
private ArrayList<ListClasses> seeListe() { ArrayList<ListClasses> list = new ArrayList<>(); File file = new File("C:/file/to/path/file.txt"); // try-with-resources会自动关闭流,无需手动在finally处理 try (FileReader fr = new FileReader(file); BufferedReader breader = new BufferedReader(fr)) { String line; // 循环读取每行 while ((line = breader.readLine()) != null) { // 跳过空行 if (line.trim().isEmpty()) { continue; } // 按分隔符拆分数据,根据你的实际格式调整分隔符 String[] parts = line.split(","); if (parts.length != 2) { // 格式错误的行跳过或提示 System.out.println("无效行格式:" + line); continue; } // 解析数据,处理可能的数值转换异常 try { String strValue = parts[0].trim(); double doubleValue = Double.parseDouble(parts[1].trim()); // 创建赋值后的对象加入集合 list.add(new ListClasses(strValue, doubleValue)); } catch (NumberFormatException e) { System.out.println("数值解析错误:" + line); } } } catch (FileNotFoundException e) { System.out.println("文件未找到:" + file.toString()); } catch (IOException e) { System.out.println("读取文件失败:" + file.toString()); } return list; }
关键改进点
- 不再创建空对象,而是解析每行数据后初始化
ListClasses的字段 - 使用
try-with-resources自动管理流资源,避免手动关闭的错误 - 增加空行、格式错误、数值解析错误的处理,避免程序崩溃
内容的提问来源于stack exchange,提问作者Alejandro
相关产品推荐
相关产品推荐

