Link to home
Start Free TrialLog in
Avatar of ralphcarter2008
ralphcarter2008

asked on

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
                      }
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

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

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

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



out = new FileWriter( outputFile);

then there's no possibility of error
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial