Search code examples
javamethodsediting

Problems regarding a Java method to edit a txt file


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");
        }
    }

I don't understand where I went wrong but it is printing "error declared" so I debugged and found after working pt1 it stops and goes to catch please help? Additional info includes: I am making a database for a restaurant and I am inputting info in txt files in the sequence item_name,item_amount,item_price so I am taking my new values from, main and passing them to the method, in theory, it first duplicates a file until it comes to the strings I wanna remove and then replaces them and goes back to copy the strings from the real files. but every time I run this I get catch.

TIA


Solution

  • While I can't answer your question straight away, I can offer a few ideas.

    First of, catch a more explicit exception, such as IOException, FileNotFoundException. It is generally good practice to have more explicit code and it's the first step towards improved error handling.

    Also do something with it, for startes you can print it in your console and use that information to debug your program. It might tell you exactly what your error is and where it is.