import java.io.File; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.FileInputStream; import java.io.IOException; import javax.swing.JFileChooser; /** * Solution code for Project 2a * Text File Dumper * User chooses a file * The program then reads each line and displays in on the console * The program should never abort, even if a bad file is chosen, * or if the file has an error. * In case of an error, the program should display information about the error, * and then terminate (use System.exit(0)) * */ public class TextFileDumper { public static void main(String[] args) { String fullFileName = getFilePath(); System.out.println("Contents of file " + fullFileName); //Create an appropriate stream or reader FileInputStream fistream; BufferedReader inReader = null; try { fistream = new FileInputStream(fullFileName); inReader = new BufferedReader(new InputStreamReader (fistream)); } catch (IOException e) { System.out.println("Couldn't open file " + fullFileName); System.out.println(e); System.exit(0); } String currentLine = null; //Do for each line on the file do { //read a line try { currentLine = inReader.readLine(); } catch (IOException e) { System.out.println("Unexpected exception while reading file: " + e); currentLine = null; //will cause loop to end } if (currentLine != null) { //print it to the console System.out.println(currentLine); } } while (currentLine != null); System.out.println("Dump of " + fullFileName + " complete."); System.exit(0); //in case there's a thread running somewhere } //end main /** Let user choose a file */ public static String getFilePath() { JFileChooser chooser = new JFileChooser(); int resultOfShow = chooser.showDialog(null, "Choose a text file"); if (resultOfShow == JFileChooser.APPROVE_OPTION) { return chooser.getSelectedFile().getAbsolutePath(); } else { //user must have canceled throw new RuntimeException("User canceled the file selection procedure"); } } } //end TextFileDumper