JAVA - Overwrite file if exists

I would like to overwrite the file if it exists. I am writing to a csv file and I dont want to append to it but rather overwrite the file if it matches the name exactly.

How would I modify it?

Date now = new Date();
formatter = new SimpleDateFormat("MMddyyyy");
s = formatter.format(now);

outputFile = "C:\\Files\\NJ" + s +".CSV";

// Error catching.
try
{
      File file = new File( outputFile );
      fileExists = file.exists();
      
      out = new FileWriter( outputFile, true );
      session.log( "Writing data to a file." );
      if (!fileExists)
      {
                      etc,etc,etc
                      }
LVL 1
ralphcarter2008Asked:
Who is Participating?
 
objectsCommented:
LordOfPorts is right, change that true to false
you can also get rid of that exists logic

Date now = new Date();
formatter = new SimpleDateFormat("MMddyyyy");
s = formatter.format(now);

outputFile = "C:\\Files\\NJ" + s +".CSV";

// Error catching.
try
{
      boolean append = false;
      File file = new File( outputFile );
     
      out = new FileWriter( outputFile, append );
      session.log( "Writing data to a file." );
   
       etc,etc,etc


0
 
CEHJCommented:
>>I would like to overwrite the file if it exists.

That's the default behaviour of Java, so you have no problem
0
 
LordOfPortsCommented:
Try passing "false" as the second parameter for the second parameter of the FileWriter constructor:

out = new FileWriter( outputFile, false );
0
 
CEHJCommented:
You don't need the second parameter at all. Just use out = new FileWriter( outputFile, false );
0
 
CEHJCommented:
Sorry, i mean



out = new FileWriter( outputFile);

then there's no possibility of error
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.