Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write to text file without overwriting in Java

Tags:

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!!");     } 
like image 335
rmp2150 Avatar asked Apr 01 '12 01:04

rmp2150


People also ask

How do I stop Java overwriting?

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.

Does FileWriter overwrite existing file?

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.

How do you override a text file in Java?

To overwrite a file in Java, set the second argument of FileWriter to false .


1 Answers

Just change PrintWriter out = new PrintWriter(log); to

PrintWriter out = new PrintWriter(new FileWriter(log, true)); 
like image 85
Qiang Jin Avatar answered Nov 10 '22 19:11

Qiang Jin