Java读取多行输入文件异常:仅正确读取前4行问题排查
我尝试读取包含多行数据的employeeInput.txt文件,但程序仅能正确读取前4行内容。
输入文件内容如下:
hv1044 jerry sein B 100500 hv8745 mary kay C 50000 P
程序预期输出所有员工的完整信息(示例如下),但目前仅能输出第一组员工的正确内容:
Employee: Jerry Sein
Position: Associate
Salary: $100000.00
Email Address: J-Sein@hv.com
相关代码如下:
import java.util.Scanner; import java.io.*; public class KosakowskiRunEmployee { public static void main(String[] args) throws IOException { File file = new File("employeeInput.txt"); double pay = 0 ; if (file.exists()) { Scanner inputFile = new Scanner(file); while (inputFile.hasNext()) { String id = inputFile.nextLine(); String name = inputFile.nextLine(); String lvl = inputFile.nextLine(); System.out.println("Employee: " + name); System.out.print("Position: "); switch (lvl) { case "A": System.out.print("Executive"); break; case "B": System.out.print("Associate"); break; case "C": System.out.print("Assistant"); break; case "D": System.out.print("Intern"); break; default: break; } System.out.println(); pay = inputFile.nextDouble(); System.out.printf("Salary: " + "$" + "%.2f", pay); System.out.println(); String[] sp = name.split(" "); int n = name.length(); char first = name.charAt(0); System.out.println("Email Address: " + first + "-" + sp[1] + "@hv.com"); System.out.println("______________________________________"); } inputFile.close(); } else { System.out.println("The file you are looking for does not exist."); } } }
问题原因与解决办法
核心问题
问题出在Scanner的nextDouble()方法上:该方法仅读取数值本身,不会读取数值后面的换行符。第一次读取完薪资100500后,输入流指针停留在该数值的换行符位置。下一次循环执行inputFile.nextLine()时,会直接读取这个空换行符作为员工ID,后续的name读取到hv8745,lvl读取到mary kay,此时再调用nextDouble()会遇到字符C,触发输入不匹配异常,程序直接终止,因此只能输出第一组员工数据。
解决方法
方法一:读取数值后跳过换行符
在pay = inputFile.nextDouble();之后添加一行代码,手动跳过数值后的换行符:
inputFile.nextLine();
这样下一次循环的nextLine()就能正确读取下一个员工的ID。
方法二:统一用nextLine()读取所有内容
将读取薪资的代码改为先按行读取字符串,再转换为double类型:
String payStr = inputFile.nextLine(); pay = Double.parseDouble(payStr);
这种方式避免了换行符残留的问题,所有数据都按行读取,逻辑更统一。
额外注意点
文件最后一行的P不属于任何员工的完整数据,循环读取到这一行时会因缺少后续的姓名、等级、薪资数据报错。可以在循环中增加判断,确保每次读取都有足够的行数据,比如提前检查inputFile.hasNextLine()的次数,或者提前确定员工数据的组数。
内容的提问来源于stack exchange,提问作者Solidus03

