// FILE HANDLING UTILITY CLASS // Frans Coenen // University of Liverpool // 20 April 2013 import java.io.*; // File and PrintWriter classes import javax.swing.*; // Contains JFileChooser class class FileHandlingUtility extends JFrame { // ------------------- FIELDS ------------------------ /** Instance of PrintWriter class */ private PrintWriter fileOutput = null; /** File instance for output. */ private File outputFileName = null; /** The file name. */ private String fileName = null; // ------------------- CONSTRUCTORS ------------------------ /* ------- Default ------ */ // ------------------- OUTPUT FILE METHODS ------------------------ /** Opens the output file ready to write data to. @return true if file succesfully opened, and false otherwise. */ public boolean openOutputFile() { // Display file dialog box JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); int result = fileChooser.showSaveDialog(this); // If cancel button selected return if (result == JFileChooser.CANCEL_OPTION) return(false); // Obtain selected file outputFileName = fileChooser.getSelectedFile(); // Dispaly error if invalid if (outputFileName == null || outputFileName.getName().equals("")) { JOptionPane.showMessageDialog(this,"Invalid File name", "Invalid File name.",JOptionPane.ERROR_MESSAGE); return(false); } else { try { fileOutput = new PrintWriter(new FileWriter(outputFileName)); fileName = outputFileName.getName(); return(true); } catch(IOException ioException) { JOptionPane.showMessageDialog(this,"Error opening File", "Error",JOptionPane.ERROR_MESSAGE); return(false); } } } // ------------------- GET METHODS ------------------------ /** Get PrintWriter object if one has been created. @return The PrintWriter objet. */ public PrintWriter getfileOutput() { return(fileOutput); } /** Get file name for opened file. @return The file name. */ public String getfileName() { return(fileName); } }