I am trying to write a method that makes a "log.txt file" if one does not already exist and then writes to the file. The problem that I am encountering is every time I call the method, it overwrites the existing log. How do I change the method so that instead of overwriting the data it just updates the file?
My Write File Method:
    File log = new File("log.txt")     try{     if(log.exists()==false){             System.out.println("We had to make a new file.");             log.createNewFile();     }     PrintWriter out = new PrintWriter(log);     out.append("******* " + timeStamp.toString() +"******* " + "\n");     out.close();     }catch(IOException e){         System.out.println("COULD NOT LOG!!");     } 
                The final way of preventing overriding is by using the final keyword in your method. The final keyword puts a stop to being an inheritance. Hence, if a method is made final it will be considered final implementation and no other class can override the behavior.
When you create a Java FileWriter you can decide if you want to overwrite any existing file with the same name, or if you want to append to any existing file.
To overwrite a file in Java, set the second argument of FileWriter to false .
Just change PrintWriter out = new PrintWriter(log); to
PrintWriter out = new PrintWriter(new FileWriter(log, true)); 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With