public static void Replace_Record(String editTerm, String newItem, String newAmount, String newPrice){
String filepath="temp_Food_Item.txt";
String tempfile= "temp_Food_Item_temp.txt";
File oldFile= new File(filepath);
File newFile=new File(tempfile);
String item=""; String quantity=""; String price="";
System.out.println("working ");
try{
//System.out.println("working pt1");
FileWriter fw= new FileWriter(tempfile,true);
BufferedWriter bw= new BufferedWriter(fw);
PrintWriter pw= new PrintWriter(bw);
x = new Scanner(new File(filepath));
x.useDelimiter("[,/n]");
//System.out.println("working pt2");
while(x.hasNext()){
//System.out.println("working pt3");
item=x.next();
quantity=x.next();
price=x.next();
if(item.equalsIgnoreCase(editTerm)){
pw.println(newItem+","+newAmount+","+newPrice);
}
else{
//System.out.println("working pt4 ");
pw.println(item+","+quantity+","+price);
}
}
x.close();
pw.flush();
pw.close();
oldFile.delete();
File dump=new File(filepath);
newFile.renameTo(dump);
}
catch(Exception e){
System.out.println("Error declared");
}
}
我不明白我哪里出错了,但它正在打印“错误声明”,所以我调试并发现在工作 pt1 后它停止并去捕获,请帮忙? 附加信息包括: 我正在为一家餐厅创建一个数据库,并且按照 item_name,item_amount,item_price 的顺序在 txt 文件中输入信息,因此理论上,我将从 main 中获取新值并将其传递给该方法,它首先复制一个文件,直到它到达我想要删除的字符串,然后替换它们,然后返回从真实文件复制字符串。但每次我运行这个我都会被捕获。
TIA
最佳答案
虽然我无法立即回答您的问题,但我可以提供一些想法。
首先,catch a more explicit exception ,如IOException、FileNotFoundException。拥有更明确的代码通常是一种很好的做法,并且这是改进错误处理的第一步。
还可以用它做一些事情,对于初学者,您可以在控制台中打印它并使用该信息 debug你的程序。它可能会准确地告诉您错误是什么以及错误在哪里。
关于java - 关于Java方法编辑txt文件的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61013723/