活鱼会逆流而上,死鱼才会随波逐流。
本讲内容:文件流
例一:写一个记事本
package b;
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class NotePad extends JFrame implements ActionListener{
JTextArea wby;
JScrollPane gd;
JMenuBar cd;
JMenu cd1;
JMenuItem ycd1,ycd2;
public static void main(String[] args) {
NotePad np=new NotePad();
}
public NotePad() {
wby=new JTextArea();
gd=new JScrollPane(wby);
cd=new JMenuBar();
cd1=new JMenu("文件(F)");
cd1.setMnemonic('F');
ycd1=new JMenuItem("打开",new ImageIcon("images/1.gif"));
//对打开按钮注册监听
ycd1.addActionListener(this);
ycd1.setActionCommand("open");
ycd2=new JMenuItem("保存",new ImageIcon("images/3.gif"));
//对保存按钮做监听
ycd2.addActionListener(this);
ycd2.setActionCommand("save");
cd1.add(ycd1); cd1.add(ycd2);
cd.add(cd1);
this.setJMenuBar(cd);
this.add(gd);
// 设置窗体属性
this.setTitle("迷你版记事本—小劲");
this.setLocation(300, 300);
this.setSize(500, 400);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("open")){
//文件选择组件
JFileChooser fch=new JFileChooser();
//设置标题
fch.setDialogTitle("请选择文件");
//(null是打开的时候使用窗口默认的方式)
fch.showOpenDialog(null);
//使该组件可见
fch.setVisible(true);
//得到用户选中的文件全路径
String filename=fch.getSelectedFile().getAbsolutePath();
FileReader fr=null;
BufferedReader br=null;
try {
fr=new FileReader(filename);
br=new BufferedReader(fr);
//从文件中读取信息并显示文本域中
String s="";
String all="";
while((s=br.readLine())!=null){
all+=s+"\r\n";
}
wby.setText(all);//放置到wby即可
} catch (Exception e1) {
e1.printStackTrace();
}finally{
try {
br.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}else if(e.getActionCommand().equals("save")){
JFileChooser fch=new JFileChooser();
fch.setDialogTitle("另存为");
fch.showSaveDialog(null);
fch.setVisible(true);
//用户希望把文件保存到何处,文件的全路径
String file=fch.getSelectedFile().getAbsolutePath();
//准备写入到指定文件
FileWriter fw=null;
BufferedWriter bw=null;
try {
fw=new FileWriter(file);
bw=new BufferedWriter(fw);
bw.write(this.wby.getText());
} catch (IOException e1) {
e1.printStackTrace();
}finally{
try {
bw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
本讲就到这里,Take your time and enjoy it