import java.awt.Color; import java.awt.BorderLayout; import java.awt.event.*; import javax.swing.*; import java.io.*; class FileIO extends JFrame implements ActionListener { JLabel text; JButton button; JPanel panel; JTextField textField; private boolean _clickMeMode = true; FileIO() { //Begin Constructor text = new JLabel("Text to save to file:"); button = new JButton("Click Me"); button.addActionListener(this); textField = new JTextField(30); panel = new JPanel(); panel.setLayout(new BorderLayout()); panel.setBackground(Color.white); getContentPane().add(panel); panel.add(BorderLayout.NORTH, text); panel.add(BorderLayout.CENTER, textField); panel.add(BorderLayout.SOUTH, button); } //End Constructor public void actionPerformed(ActionEvent event){ Object source = event.getSource(); //The equals operator (==) is one of the few operators //allowed on an object in the Java programming language if (source == button) { String s = null; //Write to file if (_clickMeMode){ try { String text = textField.getText(); byte b[] = text.getBytes(); String outputFileName = System.getProperty("user.home", File.separatorChar + "home" + File.separatorChar + "zelda") + File.separatorChar + "text.txt"; FileOutputStream out = new FileOutputStream(outputFileName); out.write(b); out.close(); } catch(java.io.IOException e) { System.out.println("Cannot write to text.txt"); } //Read from file try { String inputFileName = System.getProperty("user.home", File.separatorChar + "home" + File.separatorChar + "zelda") + File.separatorChar + "text.txt"; File inputFile = new File(inputFileName); FileInputStream in = new FileInputStream(inputFile); byte bt[] = new byte[(int)inputFile.length()]; in.read(bt); s = new String(bt); in.close(); } catch(java.io.IOException e) { System.out.println("Cannot read from text.txt"); } //Clear text field textField.setText(""); //Display text read from file text.setText("Text retrieved from file:"); textField.setText(s); button.setText("Click Again"); _clickMeMode = false; } else { //Save text to file text.setText("Text to save to file:"); textField.setText(""); button.setText("Click Me"); _clickMeMode = true; } } } public static void main(String[] args){ FileIO frame = new FileIO(); frame.setTitle("Example"); WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }; frame.addWindowListener(l); frame.pack(); frame.setVisible(true); } }