、
上面为效果图:
下面为代码:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.omg.CORBA.portable.OutputStream;
public class File_sava_open extends JFrame implements ActionListener {
/**
* @param args
*/
JPanel jp;
JButton jb1, jb2, jb3;
JEditorPane jep;
JFileChooser jfc;
public static void main(String[] args) {
// TODO Auto-generated method stub
File_sava_open mh = new File_sava_open();
}
public File_sava_open() {
// 定义一个JP
jp = new JPanel();
jep = new JEditorPane();
jb1 = new JButton("打开");
jb1.setActionCommand("dk");
jb1.addActionListener(this);
jb2 = new JButton("保存");
jb2.setActionCommand("bc");
jb2.addActionListener(this);
jb3 = new JButton("取消");
// 添加组件
jp.add(jb1);
jp.add(jb2);
jp.add(jb3);
this.add(jep);
this.add(jp, "South");
// 设置界面
this.setLocation(300, 200);
this.setTitle("记事本");
this.setSize(300, 400);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
//响应打开按钮 并显示所选文件内容
if (arg0.getActionCommand().equals("dk")) {
System.out.println();
jfc = new JFileChooser();
int returnval = jfc.showOpenDialog(this);
if (returnval == jfc.APPROVE_OPTION) {
String filename = jfc.getSelectedFile().getAbsolutePath();
try {
InputStream is = new FileInputStream(filename);
BufferedInputStream bis=new BufferedInputStream(is);
byte[] by = new byte[is.available()];
bis.read(by);
String str = new String(by);
jep.setText(str);
bis.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
if (arg0.getActionCommand().equals("bc")) {
//响应保存按钮 并显示所选文件内容
System.out.println();
jfc = new JFileChooser();
int m = jfc.showSaveDialog(this);
if (m == jfc.APPROVE_OPTION) {
String filename = jfc.getSelectedFile().getAbsolutePath();
try {
FileOutputStream os = new FileOutputStream(filename,true);
BufferedOutputStream bos=new BufferedOutputStream(os);
String str=jep.getText();
bos.write(str.getBytes());
bos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}