【问题标题】:Problems regarding a Java method to edit a txt file关于编辑txt文件的Java方法的问题
【发布时间】:2020-07-15 17:33:15
【问题描述】:
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 后调试并发现它停止并去捕捉请帮助? 附加信息包括: 我正在为一家餐馆创建一个数据库,并且我在 txt 文件中以 item_name,item_amount,item_price 的顺序输入信息,所以理论上我从 main 中获取我的新值并将它们传递给方法,它首先复制一个文件,直到它涉及我要删除的字符串,然后替换它们并返回以从真实文件中复制字符串。但每次我运行这个我都会被抓住。

TIA

【问题讨论】:

  • 您应该打印ExceptionstackTrace 而不仅仅是"Error declared",它永远不会告诉您到底发生了什么,但异常堆栈跟踪会做。
  • 您可以使用 e.printStacktrace() 打印堆栈跟踪,这将打印到标准错误

标签: java methods editing


【解决方案1】:

大家好,感谢您帮助我解决了这个问题,但我已经设法解决了它除了我们 Gucci 之外,我无法识别我调用的是哪个文件,谢谢你们

【讨论】:

    【解决方案2】:

    虽然我不能马上回答你的问题,但我可以提供一些想法。

    首先,catch a more explicit exception,比如IOException、FileNotFoundException。拥有更明确的代码通常是一种好习惯,这是改进错误处理的第一步。

    也可以用它做一些事情,一开始你可以在你的控制台中打印它并将该信息用于debug你的程序。它可能会准确地告诉您您的错误是什么以及它在哪里。

    【讨论】:

    • 捕获更具体的异常是最佳实践,但如果不打印堆栈跟踪,这可能对查找异常原因没有多大帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多