// 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; /** Array structure for storing file input. */ private String[] dataArray = 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); } } } // ------------------- INPUT FILE METHODS ------------------------ /** Method to start process of openning a file for input, reading the content, and storing the comtent in the dataArray string array structure. @return true if successful, false otherwise. */ public boolean openInputFile() { // Display file dialog so user can select file to open JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); int result = fileChooser.showOpenDialog(this); // If cancel button selected return if (result == JFileChooser.CANCEL_OPTION) return(false); // Obtain selected file and create File object File inputFileName = fileChooser.getSelectedFile(); // Read file if readabale (i.e. not a directory etc.). if (checkFileName(inputFileName)) { if (readFile(inputFileName)) return(true); else return(false); } else return(false); } /** Method to start process of openning a file for input, reading the content, and storing the comtrnt in the dataArray string array structure where the file name is known. @param stringFileName the given file name as a string. @return true if successful, false otherwise. */ public boolean openInputFile(String stringFileName) { // Create File object File inputFileName = new File(stringFileName); // Read file if readabale (i.e. not a direcrory etc.). if (checkFileName(inputFileName)) { if (readFile(inputFileName)) return(true); else return(false); } else return(false); } /** Checks nature of the selected input file name to make sure it is readable. @param fileName the File object to be checked @return false if selected file is a directory, access is denied or is not a file name; and true otherwise. */ private boolean checkFileName(File fileName) { boolean fileOK = true; // Check if file name exist if (fileName.exists()) { // Check if file name is readable if (fileName.canRead()) { // Check if file name is actually a file if (fileName.isFile()) return(fileOK); else JOptionPane.showMessageDialog(null, "FILE ERROR: File is a directory"); } else JOptionPane.showMessageDialog(null, "FILE ERROR: Access denied"); } else JOptionPane.showMessageDialog(null, "FILE ERROR: No such file!"); // Return return(!fileOK); } /** Reads the designated input file. Need to read it twice, once to dimension the dataArray array structure and once to populate that structure. @param fileName the File object for the file to be loaded. @return true if successful, false otherwise. */ private boolean readFile(File fileName) { boolean success = false; // Dimension data structure int numLines = getNumberOfLines(fileName); if (numLines>0) { // Dimension dataArray storage structure dataArray = new String[numLines]; // Now read file if (readInputDataSet(fileName)) success = true; } // Return return(success); } /** Reads input data from given file and places it in the dataArray array structure. @param fileName the File to read. @return true if successful, false otherwise. */ private boolean readInputDataSet(File fileName) { boolean success = false; // Try-catch block try { FileReader file = new FileReader(fileName); BufferedReader fileInput = new BufferedReader(file); // Get first row. String line = fileInput.readLine(); // Process rest of file int rowIndex=0; while (line != null) { // Process line dataArray[rowIndex] = line; // Increment first (row) index in 2-D data array rowIndex++; // get next line line = fileInput.readLine(); } success = true; // Close file fileInput.close(); } catch(IOException ioException) { JOptionPane.showMessageDialog(null,"Unknown error reading " + "file: " + fileName + "\n","FILE INPUT ERROR", JOptionPane.ERROR_MESSAGE); } // Return return(success); } /** Method to determined number of lines/records in input file. @param fileName the File to read. @return the number of rows in the given file (0 if error). */ private int getNumberOfLines(File fileName) { int counter = 0; // Try-catch block try { // Open the file FileReader file = new FileReader(fileName); BufferedReader fileInput = new BufferedReader(file); // Loop through file incrementing counter starting with first row. String line = fileInput.readLine(); while (line != null) { counter++; line = fileInput.readLine(); } // Close file fileInput.close(); } catch(IOException ioException) { JOptionPane.showMessageDialog(null,"Unknown error reading " + "file: " + fileName + "\n","FILE INPUT ERROR", JOptionPane.ERROR_MESSAGE); } // Return counter return(counter); } // ------------------- 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); } /** Get the dataArray array structure @return reference to dataArray. */ public String[] getDataArray() { return(dataArray); } // ------------------- OUTPUT METHODS ------------------------ /** Method to output contents of dataArray storage structure to screen. */ public void outputDataArray() { for (int index=0;index