-5

My code will write 8-10 strings every time a program runs but when my program is running second time it is not creating a new file instead it is appending new data in same file because of which file size is increasing. My code is as follows:

File file=new File("user. txt") ;
Printwriter pw=new PrintWriter(new BufferedWriter(new FileWriter(file. getAbsoluteFile(), true) ) ;

I know true means appending content. But when I remove true from code it is overriding my content in file and writing only last string to my file. I want to create a fresh file every time my code runs but want full data everytime my code runs not only last string.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • 1
    Please show a [mcve]... You have no code in your question that writes anything – OneCricketeer Jan 10 '18 at 05:53
  • I have problem in this part that's why posted this only –  Jan 10 '18 at 05:54
  • 1
    If you have a problem writing the full content it would be helpful to show the code that does the write. – Henry Jan 10 '18 at 05:55
  • Possible duplicate of [How to append text to an existing file in Java](https://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java) – Shubhendu Pramanik Jan 10 '18 at 05:55
  • The problem is, that you use the same file name for each time, when the program runs. You have to find a way to change the file name in `new File();` – Geshode Jan 10 '18 at 05:57
  • You want to append to the file *and* create a new file? So one file should contain everything and the other file contains the old strings plus the new strings? – matt Jan 10 '18 at 05:57
  • At the moment, your problem statement is: "I have a problem writing data to a file. Here I show opening the file, but not writing it". Please [edit] the post to include more code – OneCricketeer Jan 10 '18 at 06:06

1 Answers1

1

Like I said in the comments, the problem is, that you always use the same file name. If you want a new file, you need a different file name.

You could use a time stamp inside the file name, for example:

String filename = LocalDateTime.now() + ".txt";
File file=new File(filename) ;
Printwriter pw=new PrintWriter(new BufferedWriter(new FileWriter(file. getAbsoluteFile(), true) ) ;

Or you can think of a different way to make the filename unique, each time the program runs.

Geshode
  • 3,600
  • 6
  • 18
  • 32