/********************************************************************** * Author: Eric Heim * Date Created: 7/14/2011 * Course: CS0007 * Description: Shows the use of the exists method to warn a user * that she is about to overwrite a file **********************************************************************/ import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class WriteExists { public static void main(String[] args) throws FileNotFoundException { Scanner keyboard = new Scanner(System.in); File myFile; PrintWriter outputFile; String filename; char response = 'N'; System.out.print("Enter the name of the file you wish to " + "write a message to: "); filename = keyboard.nextLine(); myFile = new File(filename); while(myFile.exists() && response != 'Y') { System.out.print("Warning! You are about to overwrite " + filename + " is this OK? (Y or N): "); response = keyboard.nextLine().toUpperCase().charAt(0); if(response != 'Y') { System.out.print("Enter the name of the file you wish to " + "write a message to: "); filename = keyboard.nextLine(); myFile = new File(filename); } } outputFile = new PrintWriter(myFile); outputFile.println("Java is fun!"); outputFile.close(); } }