如何用Scanner按制表符读取文本文件并存入ArrayList?代码是否正确?
代码正确性分析与修正
需求说明
要读取的Customer.txt是制表符(U+0009)分隔的文本文件,每行包含8个字段,示例内容如下:
yx
Yong 123 Male 2002 999 jay@ NO234
paulPaul Tan 123 Male 2002 999 kkk nnn
原代码的问题
你写的代码存在核心逻辑错误:
- 错误混用了
Scanner.nextLine()和制表符分隔规则:nextLine()是读取到换行符为止的整行内容,完全无视你设置的\t分隔符,导致每次循环读取8行数据而非一行里的8个字段,直接造成字段错位,甚至触发NoSuchElementException。 - 末尾多余的
s.nextLine()会额外跳过一行数据,进一步破坏读取逻辑。
修正方案
方案1:基于Scanner分隔符读取字段
设置分隔符为制表符或换行符,用next()读取每个字段:
public static void readCustomer() { try { Scanner s = new Scanner(new File("Customer.txt")); // 用制表符或换行符作为分隔符,兼容每行的字段结束 s.useDelimiter("\\t|\\n"); while (s.hasNext()) { String userName = s.next(); String fullName = s.next(); String password = s.next(); String gender = s.next(); String birthyear = s.next(); String phone = s.next(); String email = s.next(); String address = s.next(); allCustomer.add(new Customer(userName, fullName, password, gender, birthyear, phone, email, address)); } s.close(); // 务必关闭资源 } catch (Exception e) { JOptionPane.showMessageDialog(null, "读取错误:" + e.getMessage()); } }
方案2:按行读取后拆分字段(更稳妥)
先读取整行,再用制表符拆分字段,同时添加格式校验:
public static void readCustomer() { try { Scanner s = new Scanner(new File("Customer.txt")); while (s.hasNextLine()) { String line = s.nextLine(); // 按制表符拆分每行数据 String[] fields = line.split("\\t"); // 校验字段数量,避免格式错误导致数组越界 if (fields.length == 8) { String userName = fields[0]; String fullName = fields[1]; String password = fields[2]; String gender = fields[3]; String birthyear = fields[4]; String phone = fields[5]; String email = fields[6]; String address = fields[7]; allCustomer.add(new Customer(userName, fullName, password, gender, birthyear, phone, email, address)); } } s.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "读取错误:" + e.getMessage()); } }
方案对比
- 方案1适合格式严格的文件,但对分隔符的设置要求精准;
- 方案2更直观,能明确处理每行数据,还能通过字段数量校验避免文件格式异常导致的崩溃,推荐使用。
内容的提问来源于stack exchange,提问作者JYX
相关产品推荐
相关产品推荐

