import java.awt.Font; import java.awt.Color; import java.awt.BorderLayout; import java.awt.event.*; import javax.swing.*; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.File; class FileIOError extends JFrame implements ActionListener { JLabel text; JButton button; JPanel panel; JTextField textField; private boolean _clickMeMode = true; FileIOError(){ //Begin Constructor text = new JLabel("Text to save to file:"); button = new JButton("Click Me"); button.addActionListener(this); textField = new JTextField(20); panel = new JPanel(); panel.setLayout(new BorderLayout()); panel.setBackground(Color.white); getContentPane().add(panel); panel.add("North", text); panel.add("Center", textField); panel.add("South", button); } //End Constructor public void actionPerformed(ActionEvent event){ Object source = event.getSource(); if(source == button){ if(_clickMeMode){ JLabel label = new JLabel(); //Write to file try{ String text = textField.getText(); byte b[] = text.getBytes(); String outputFileName = System.getProperty("user.home", File.separatorChar + "home" + File.separatorChar + "monicap") + File.separatorChar + "text.txt"; File outputFile = new File(outputFileName); FileOutputStream out = new FileOutputStream(outputFile); 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 + "monicap") + File.separatorChar + "text.txt"; File inputFile = new File(inputFileName); FileInputStream in = new FileInputStream(inputFile); byte bt[] = new byte[(int)inputFile.length()]; int i; i = in.read(bt); String s = new String(bt); label.setText(s); in.close(); }catch(java.io.IOException e){ System.out.println("Cannot read from text.txt"); } text.setText("Text retrieved from file:"); button.setText("Click Again"); _clickMeMode = false; } else { 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); } }