//Example14
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.*;
public class Example14{
JTextField tf01=new JTextField("",20);
JTextField tf02=new JTextField("",20);
//main
public static void main(String ar[]){
Example14 sample=new Example14();
}
//constructor
Example14(){
JFrame f=new JFrame("File IO");
f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
JButton bt01=new JButton("Open");
bt01.setActionCommand("Open");
bt01.addActionListener(new PushButtonActionListener(f));
JButton bt02=new JButton("Save");
bt02.setActionCommand("Save");
bt02.addActionListener(new PushButtonActionListener(f));
JPanel p1=new JPanel();
p1.add(bt01);
p1.add(bt02);
f.getContentPane().add(p1,BorderLayout.NORTH);
JPanel p2=new JPanel();
p2.add(tf01);
p2.add(tf02);
f.getContentPane().add(p2,BorderLayout.CENTER);
f.setSize(640,400);
f.setVisible(true);
}
//action listener
private class PushButtonActionListener implements ActionListener{
JFrame f = null;
public PushButtonActionListener(JFrame af) {
this.f = af;
}
public void actionPerformed(ActionEvent ae){
if(ae.getActionCommand()=="Open"){
tf01.setText("");
tf02.setText("");
JFileChooser fc=new JFileChooser(System.getProperty("user.dir"));
int fd=fc.showOpenDialog(f);
try{
if(fd==JFileChooser.APPROVE_OPTION){
FileInputStream fi=new FileInputStream(fc.getSelectedFile());
BufferedReader br=new BufferedReader(new InputStreamReader(fi));
String s01=br.readLine();
if(s01 != null) tf01.setText(s01);
String s02=br.readLine();
if(s02 != null) tf02.setText(s02);
br.close();
fi.close();
}
}
catch(Exception ex){}
}else if(ae.getActionCommand()=="Save"){
JFileChooser fc=new JFileChooser(System.getProperty("user.dir"));
int fd=fc.showSaveDialog(f);
try{
if(fd==JFileChooser.APPROVE_OPTION){
FileOutputStream fo=new FileOutputStream(fc.getSelectedFile());
PrintStream ps=new PrintStream(fo);
ps.println(tf01.getText());
ps.println(tf02.getText());
ps.close();
fo.close();
}
}
catch(Exception ex){}
}
}
}
}