Example - Writing to an Existing File

import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileWriter;
import java.io.File;

public class FileExists
{
    public static void main(String[] args)
    {
        InputStreamReader convert = new InputStreamReader(System.in);
        BufferedReader stdin = new BufferedReader(convert);
        String instr;
        File outfile = new File("textfile.out");
        boolean append = true;
        try
        {
            if (outfile.exists())
            {
                System.out.print("File already exists: do you want to overwrite ");
		System.out.println("or append (enter o or a)");
                instr = stdin.readLine();
                if (instr.equals("o"))
                    append = false;
            }
            FileWriter fout = new FileWriter("textfile.out",append);
            PrintWriter fileout = new PrintWriter(fout,true);
            System.out.print("Enter a string: ");
            instr = stdin.readLine();
            fileout.println(instr);
            fileout.flush();
            fileout.close();
        }
        catch(IOException e) {}
    }

}

Output:

C:\cafe1.8\Mine>type textfile.out
File not found - textfile.out

C:\cafe1.8\Mine>java FileExists
Enter a string: this will be the first line

C:\cafe1.8\Mine>type textfile.out
this will be the first line

C:\cafe1.8\Mine>java FileExists
File already exists: do you want to overwrite or append (enter o or a)
a
Enter a string: this will be added

C:\cafe1.8\Mine>type textfile.out
this will be the first line
this will be added

C:\cafe1.8\Mine>java FileExists
File already exists: do you want to overwrite or append (enter o or a)
o
Enter a string: the old lines will be gone

C:\cafe1.8\Mine>type textfile.out
the old lines will be gone

C:\cafe1.8\Mine>


Email Me | Office Hours | My Home Page | Department Home | MCC Home Page