import java.io.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; /** Illustrates several things about file handling in Java. @author Melvin Fitting @version April, 2003 */ public class ReadWriteFile extends JFrame implements ActionListener { private JButton readButton, writeButton; public static void main(String[] args) { ReadWriteFile rwf = new ReadWriteFile(); } public ReadWriteFile() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setTitle("File reading/writing demo"); getContentPane().setLayout(new FlowLayout()); writeButton = new JButton("Write to a file"); writeButton.addActionListener(this); getContentPane().add(writeButton); readButton = new JButton("Read from a file"); readButton.addActionListener(this); getContentPane().add(readButton); setSize(400,300); setVisible(true); } public void actionPerformed(ActionEvent e) { if (e.getSource()==readButton) { StringBuffer sb = new StringBuffer(); try { JFileChooser fc = new JFileChooser(); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File datafile = fc.getSelectedFile(); DataInputStream infile = new DataInputStream(new FileInputStream(datafile)); try { while(true) sb.append(infile.readUTF() + " "); } catch(EOFException eof) { infile.close(); } } } catch(IOException ex1) {System.out.println("IO error");} getContentPane().removeAll(); getContentPane().add(writeButton); getContentPane().add(readButton); JTextArea result = new JTextArea(sb.toString()); result.setLineWrap(true); result.setWrapStyleWord(true); result.setSize(250,400); result.setEditable(false); getContentPane().add(result); validate(); } else if (e.getSource()==writeButton) { try { JFileChooser fc = new JFileChooser(); int returnVal = fc.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File datafile = fc.getSelectedFile(); DataOutputStream outfile = new DataOutputStream(new FileOutputStream(datafile)); boolean finished = false; do { String word = JOptionPane.showInputDialog("Enter a string. Enter nothing, to stop."); if (word.length()>0) outfile.writeUTF(word); else finished = true; }while(!finished); outfile.close(); } } catch(IOException ex2) {System.out.println("IO Error");} } } }