import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.FileNotFoundException; 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 * @return the opened file */ public static FileReader getNameAndOpenInput() throws IOException { int tries = 1; String fileName; while(true) { fileName = JOptionPane.showInputDialog("Enter the input file name"); if( fileName == null ) { return null; } // end if try { return new FileReader(fileName); } catch( FileNotFoundException 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"); if( fileName == null ) { return null; } // end if try { return new FileWriter(fileName); } 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