We help IT Professionals succeed at work.
Get Started

How do I erase everything in my file before adding new stuff?

Mickeys
Mickeys asked
on
162 Views
Last Modified: 2012-05-07
If I run the method below it is just adding stuff to my transaction.txt file. I want it to erase evertyning in it and just add my new stuff. How is this done?
public void writeToFile(String n) {
 
        //Deklaration
        FileWriter pw = null;
 
        try {
            //Skapa en StringBuffer
            StringBuffer buf = new StringBuffer();
 
            // Lägg till det som ska in i filen.
            buf.append(n).append(" ").append("\r\n");
 
            //Öppna filen
            File outFile = new File("Transaction.txt");
            JOptionPane.showMessageDialog(null, "Filen sparad som Transaction.txt");
            //Finns filen?
            if (!outFile.exists()) {
                outFile.createNewFile();
            }
 
            //Skriv sist i filen
            pw = new FileWriter(outFile, true);
            pw.write(buf.toString());
 
        } catch (Exception e) {
            System.err.print("Gick ej öppna. Avslutar");
            System.exit(-1);
        } //end catch
        finally {
            //Stäng filen
            if (pw != null) {
                try {
                    pw.flush();
                    pw.close();
                } catch (IOException e) {
                    System.err.print("Gick ej stänga filen. Avslutar");
                    System.exit(-1);
                } //end catch
            } //end if
        } //end finnaly
    } //end writeToFile

Open in new window

Comment
Watch Question
CERTIFIED EXPERT
Distinguished Expert 2020
Commented:
This problem has been solved!
Unlock 1 Answer and 2 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE