Java如何从文本文件单行读取多类型员工数据并正确解析?
解决CSV格式员工数据读取的问题
你的问题根源在于Scanner.next()默认用空白字符作为分隔符,而你的数据是用逗号分隔的,且姓名字段包含空格——这就导致Scanner把逗号和空格都当成了分割点,把32483, William Ellis, 25.50拆成了"32483,"、"William"、"Ellis,"、"25.50",自然会出现ID带逗号、姓名不完整,还把Ellis,当成薪资解析报错的问题。
下面给你两种简单可靠的解决方案:
方案1:按行读取后拆分字段
先读取整行数据,再根据逗号拆分,最后把中间的字段拼接成完整姓名(因为姓名可能包含多个空格分隔的部分,但不会有逗号):
import java.util.HashMap; import java.util.Scanner; public class EmployeeReader { public static void main(String[] args) { HashMap<String, Employee> empmap = new HashMap<>(); try (Scanner inputFile = new Scanner("employee.txt")) { // 替换为你的文件路径 while (inputFile.hasNextLine()) { String line = inputFile.nextLine().trim(); if (line.isEmpty()) continue; // 跳过空行 // 按逗号拆分每行 String[] parts = line.split(","); if (parts.length < 3) { System.err.println("无效的行格式:" + line); continue; } // 提取ID(第一个字段,去除前后空格) String empID = parts[0].trim(); // 提取薪资(最后一个字段,转为double) double wage = Double.parseDouble(parts[parts.length - 1].trim()); // 拼接姓名:从第1个到倒数第2个字段,去除每个部分的空格后拼接 StringBuilder fullName = new StringBuilder(); for (int i = 1; i < parts.length - 1; i++) { if (i > 1) fullName.append(" "); fullName.append(parts[i].trim()); } empmap.put(empID, new Employee(empID, fullName.toString(), wage)); } } catch (Exception e) { e.printStackTrace(); } } } // 假设你的Employee类是这样的 class Employee { private String empID; private String fullName; private double wage; public Employee(String empID, String fullName, double wage) { this.empID = empID; this.fullName = fullName; this.wage = wage; } }
方案2:用正则表达式匹配整行
如果想更简洁,可以用正则表达式直接捕获每行的三个字段,确保ID、姓名、薪资被正确提取:
import java.util.HashMap; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class EmployeeReader { public static void main(String[] args) { HashMap<String, Employee> empmap = new HashMap<>(); // 正则表达式:匹配ID(逗号前的内容)、姓名(两个逗号之间的内容)、薪资(最后逗号后的内容) Pattern linePattern = Pattern.compile("^(.*?),\\s*(.*?),\\s*(.*)$"); try (Scanner inputFile = new Scanner("employee.txt")) { while (inputFile.hasNextLine()) { String line = inputFile.nextLine().trim(); if (line.isEmpty()) continue; Matcher matcher = linePattern.matcher(line); if (matcher.matches()) { String empID = matcher.group(1).trim(); String fullName = matcher.group(2).trim(); double wage = Double.parseDouble(matcher.group(3).trim()); empmap.put(empID, new Employee(empID, fullName, wage)); } else { System.err.println("无法解析的行:" + line); } } } catch (Exception e) { e.printStackTrace(); } } }
两种方案都能解决你的问题,方案1更适合新手理解,方案2更简洁优雅。如果你的数据中姓名可能包含逗号(虽然你示例里没有),那建议用专门的CSV解析库,但针对你当前的场景,上面两种方法完全够用。
内容的提问来源于stack exchange,提问作者moosebomber
相关产品推荐
相关产品推荐

