/** FileOps.java provides commonly needed file operations.
 *  @author Joel Adams, for Alice+Java.
 */

import java.util.Scanner;
import java.io.*;            // File, PrintWriter, ...

public class FileOps {
 public static Scanner kbd = new Scanner(System.in);

 /** Prompt for a file-name and return a File to it
  * @param prompt, a String asking the user to enter a file-name.
  * @return a File for the file whose name the user enters
  */
 public static File promptForFile(String prompt) {
	 System.out.print(prompt);
	 String fileName = kbd.next();
	 return new File(fileName);
 }
 
/** Prompt for a file-name, and return a PrintWriter for it.
  * @param prompt, a String, asking the user to enter a file-name
  * @return a Scanner for the file whose name the user enters.
  */
 public static Scanner promptForFileIn(String prompt) {
	 Scanner result = null;
	 boolean done = false;
	 do {
	    try {
			 File inFile = promptForFile(prompt);
			 result = new Scanner(inFile);
			 done = true;
	    } catch (FileNotFoundException fnfe) {
	    	quitOrTryAgain("Unable to open input file");
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
	 } while (!done);
	 
	 return result;
 }

 /** Display error message, ask the user if they want to quit or try again
  * @param errorMessage, a String
  * Postcondition: If the user wants to quit, the program terminates.
  */
private static void quitOrTryAgain(String errorMessage) {
	System.out.println(errorMessage);
	System.out.println("Do you want to quit (q) or try again (a)? ");
	char answer = kbd.next().charAt(0);
	if (answer == 'q' || answer == 'Q') {
		System.exit(1);
	}
}

 /** Prompt for a file-name and return a PrintWriter for it.
  * @param prompt, a String asking the user to enter a file-name.
  * @return a PrintWriter for the file whose name the user enters
  */
 public static PrintWriter promptForFileOut(String prompt) {
	 PrintWriter result = null;
	 boolean done = false;
	 do {
		 try {
			 File outFile = promptForFile(prompt);
			 result = new PrintWriter(outFile);
			 done = true;
		 } catch (FileNotFoundException fnfe) {
			 quitOrTryAgain("Unable to open output file");
		 } catch (Exception e) {
			 e.printStackTrace();
		 }
	 } while (!done);
	 
	 return result;
 }
}
