package demo; import java.awt.TextArea; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; import javax.swing.JFileChooser; import javax.swing.JFrame; /** * Class that will handle the File Input and Output for the Program. * * @author uphusar. Created Oct 1, 2011. */ public class FileIO { private JFrame frame; private TextArea textArea; private JFileChooser fc; /** * Constructs a handler for File I/O. * * @param frame * @param textArea */ public FileIO(JFrame frame, TextArea textArea) { this.frame = frame; this.textArea = textArea; this.fc = new JFileChooser(); } /** * Saves the text in the TextArea to a text file. * */ protected void save() { int returnValue = this.fc.showSaveDialog(this.frame); if (returnValue == 0) { try { PrintWriter pw = new PrintWriter(this.fc.getSelectedFile()); pw.write(this.textArea.getText()); pw.close(); } catch (FileNotFoundException exception) { // Do Nothing } } } /** * Opens a text file and displays it in the TextArea. * * @throws FileNotFoundException * */ protected void open() { int returnValue = this.fc.showOpenDialog(this.frame); try { if (returnValue == 0) { Scanner in = new Scanner(this.fc.getSelectedFile()); while (in.hasNextLine()) { this.textArea.append(in.nextLine()); if (in.hasNextLine()) { this.textArea.append("\n"); } } in.close(); } } catch (FileNotFoundException exception) { // TODO Auto-generated catch-block stub. exception.printStackTrace(); } } }