import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.FileNotFoundException; import java.util.Scanner; import javax.swing.JOptionPane; /** * A class to open files for input/output after prompting for the file name * * @author Bill Kraynek */ public class OpenFiles { /** * Prompts the user for a file name and opens the file for input @returns a * Scanner object to read the file */ public static Scanner getNameAndOpenInput() throws IOException { int tries = 1; String fileName; while (true) { fileName = JOptionPane.showInputDialog("Enter the input file name"); try { return new Scanner(new File(fileName)); } catch(NullPointerException e) { return null; } catch (IOException e) { if (tries > 2) { throw e; } JOptionPane.showMessageDialog(null, fileName + " could not be opened. Try again."); tries++; if (tries == 3) { JOptionPane.showMessageDialog(null, "This is your last try!"); } } // try/catch } // end while } // end getNameAndOpenInput /** * Prompts the user for a file name and opens the file for output * * @return the opened file */ public static FileWriter getNameAndOpenOutput() throws IOException { String fileName; int tries = 1; while (true) { fileName = JOptionPane.showInputDialog("Enter the output file name"); try { return new FileWriter(fileName); } catch(NullPointerException e) { return null; } catch (IOException e) { if (tries > 2) { throw e; } JOptionPane.showMessageDialog(null, fileName + " could not be opened. Try again."); tries++; if (tries == 3) { JOptionPane.showMessageDialog(null, "This is your last try!"); } } // try/catch } // end while } // end getNameAndOpenOutput } // end OpenFiles