package solution; import java.awt.TextArea; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; /** * Class that will handle the File Input and Output for the Program. * * @author uphusar. Created Oct 1, 2011. */ public class FileIO { private JFileChooser fc = new JFileChooser(); private JFrame frame; private TextArea textArea; /** * Constructs a handler for File I/O. * * @param frame * @param textArea */ public FileIO(JFrame frame, TextArea textArea) { this.frame = frame; this.textArea = textArea; } /** * Saves the text in the TextArea to a text file. * */ protected void save() { this.fc.setFileFilter(new FileTypeFilter()); String text = this.textArea.getText(); int returnVal = this.fc.showSaveDialog(this.frame); if (returnVal == 0) { String sFile = this.fc.getSelectedFile().toString(); String ext = sFile.substring(sFile.length() - 4); if (!ext.equals(".txt")) { sFile += ".txt"; } try { PrintWriter out = new PrintWriter(sFile); out.write(text); out.close(); } catch (IOException exception) { // Do Nothing. } } } /** * Opens a text file and displays it in the TextArea * * @throws FileNotFoundException * */ protected void open() { this.fc.setFileFilter(new FileTypeFilter()); int returnVal = this.fc.showOpenDialog(this.frame); String ext = ""; String sFile = ""; File file = new File(""); if (returnVal == 0) { file = this.fc.getSelectedFile(); sFile = file.toString(); ext = sFile.substring(sFile.length() - 3); } if (returnVal == 0 && ext.equals("txt")) { // Open the file, EX: FileDoesntExist, Display Text. this.textArea.setText(""); Scanner in; try { in = new Scanner(file); while (in.hasNextLine()) { this.textArea.append(in.nextLine()); if (in.hasNextLine()) { this.textArea.append("\n"); } } in.close(); this.frame.setTitle(sFile); } catch (FileNotFoundException exception) { JOptionPane.showMessageDialog(this.frame, "The file you requested does not exist", "File Not Found", JOptionPane.PLAIN_MESSAGE); } } else { if (!ext.equals("txt") && returnVal == 0) { JOptionPane.showMessageDialog(this.frame, "You must select a *.txt file.", "Incorrect File Type", JOptionPane.PLAIN_MESSAGE); } } } }