使用Java修改文本文件记录时运行报错无法按ID更新内容如何解决
Java文本更新功能修复方案
核心问题点
- 输入缓冲区换行符残留:调用
input.nextInt()获取ID后,输入缓冲区会残留未读取的换行符,后续执行input.nextLine()获取商品描述时会直接读取到空字符串,导致数据异常。 - 分隔符适配问题:读取文件时设置的分隔符仅适配
\n换行,Windows系统下文件换行符为\r\n,会导致读取内容携带多余的\r字符,触发类型转换异常。 - 异常处理不完善:catch块仅打印笼统的Error提示,无法定位具体报错原因,不利于问题排查。
- 临时文件写入模式错误:创建FileWriter时设置了append=true追加模式,多次运行会导致临时文件残留旧数据,最终写入的文件内容混乱。
- 读取逻辑缺陷:使用
x.next()读取商品描述时,如果描述内容包含空格会被截断,同时读取数值时混用nextFloat()和double类型接收,可能触发精度或者类型转换异常。
修复后完整代码
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.util.Scanner; public class Update { public static Scanner x; public void update() { Scanner input = new Scanner(System.in); String filepath = "Item.txt"; System.out.println("Enter the ID of the item"); int editTerm = input.nextInt(); // 修复1:读取完int后消耗残留的换行符 input.nextLine(); int newID = editTerm; System.out.println("Enter the description of the Item"); String newDescription = input.nextLine(); System.out.println("Enter the current price of the item"); double newunitPrice = input.nextDouble(); System.out.println("Enter the current amount of stock"); int newqtyinStock = input.nextInt(); double newtotalPrice = newunitPrice * newqtyinStock; editRecord(filepath,editTerm,newID,newDescription,newunitPrice,newqtyinStock,newtotalPrice); System.out.println(newID + "," + newDescription + "," + newunitPrice + "," + newqtyinStock + "," + newtotalPrice + " has been updated on the system"); } public static void editRecord(String filepath, int editTerm, int newID, String newDescription, double newunitPrice, int newqtyinStock, double newtotalPrice) { String tempFile = "temp.txt"; File oldFile = new File(filepath); File newFile = new File(tempFile); int ID = 0; String Description = ""; double unitPrice = 0.0; int qtyinStock = 0; double totalPrice = 0.0; try { // 修复2:关闭追加模式,每次覆盖临时文件 FileWriter fw = new FileWriter(tempFile, false); BufferedWriter bw = new BufferedWriter(fw); PrintWriter pw = new PrintWriter(bw); x = new Scanner(new File(filepath)); // 修复3:适配Windows和Linux换行符,同时忽略前后空白字符 x.useDelimiter(",|\\R"); while(x.hasNext()) { ID = x.nextInt(); Description = x.next().trim(); unitPrice = x.nextDouble(); qtyinStock = x.nextInt(); totalPrice = x.nextDouble(); if(ID == editTerm) { pw.println(newID + "," + newDescription + "," + newunitPrice + "," + newqtyinStock + "," + newtotalPrice); } else { pw.println(ID + "," + Description + "," + unitPrice + "," + qtyinStock + "," + totalPrice); } } x.close(); pw.flush(); pw.close(); // 增加删除和重命名成功校验,避免权限问题导致操作失败 if(!oldFile.delete()){ throw new Exception("原文件删除失败,请检查文件是否被占用"); } if(!newFile.renameTo(new File(filepath))){ throw new Exception("临时文件重命名失败,请检查权限"); } } catch (Exception e) { // 修复4:打印具体异常栈信息,方便排查问题 System.out.println("操作失败,错误原因:" + e.getMessage()); e.printStackTrace(); } } }
补充注意点
- 确保Item.txt的每行数据格式严格为
ID,描述,单价,库存,总价,无空行、无多余字符,否则会触发读取异常。 - 运行程序时确保当前用户对Item.txt所在目录有读写权限,避免文件操作失败。
内容的提问来源于stack exchange,提问作者fmann
相关产品推荐
相关产品推荐

