记事本读写文件功能的实现

来源:互联网 发布:arm多核编程 编辑:程序博客网 时间:2024/04/27 13:54
public class Notepad extends JFrame implements ActionListener{


//定义需要的组件
JTextArea jta = null;
//菜单条
JMenuBar jmb = null;
//第一JMenu
JMenu jm1 = null;
//定义JMenuItem
JMenuItem jmi1 = null;
JMenuItem jmi2 = null;

public static void main(String[] args) {
Notepad np = new Notepad();
}

//构造函数
public Notepad(){
//创建jta
jta = new JTextArea();
jmb = new JMenuBar();
jm1 = new JMenu("文件");
//设置助记符
jm1.setMnemonic('F');
jmi1 = new JMenuItem("打开");
//注册监听
jmi1.addActionListener(this);
jmi1.setActionCommand("open");
jmi2 = new JMenuItem("保存");

//对保存菜单处理
jmi2.addActionListener(this);
jmi2.setActionCommand("save");

//加入
this.setJMenuBar(jmb);
//把jm1放入jmb
jmb.add(jm1);
//把item放入Menu
jm1.add(jmi1);
jm1.add(jmi2);
//放入到JFrame
this.add(jta);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400,300);
this.setVisible(true);
}


@Override
public void actionPerformed(ActionEvent e) {
// 判断时哪个菜单被选中
if (e.getActionCommand().equals("open")) {
//System.out.println("open");

//重要组件:JFileChooser
//文件选择组件
JFileChooser jfc1 = new JFileChooser();
//设置名字
jfc1.setDialogTitle("请选择文件......");
//默认方式
jfc1.showOpenDialog(null);
//显示
jfc1.setVisible(true);

//得到用户选择文件的全路径
String filename = jfc1.getSelectedFile().getAbsolutePath();
//System.out.println(filename);
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(filename);
br = new BufferedReader(fr);

//从文件中读取信息并显示到jta
String s = "";
String allContent = "";
while ((s = br.readLine())!=null) {
//System.out.println(s);  //将文件内容输出到控制台
//输出到磁盘
allContent+=s+"\r\n";
}
//放置大jta即可
jta.setText(allContent);

} catch (Exception e1) {
}finally{
try {
br.close();
fr.close();
} catch (Exception e1) {
e1.printStackTrace();
}
    }
}else if (e.getActionCommand().equals("save")) {
//出现保存对话框
JFileChooser jfc = new JFileChooser();
jfc.setDialogTitle("另存为......");
//按默认的方式显示
jfc.showSaveDialog(null);
jfc.setVisible(true);

//得到用户希望把文件保存到何处--文件全路径
String file = jfc.getSelectedFile().getAbsolutePath();

//准备写入到指定文件
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(file);
bw = new BufferedWriter(fw);
//自己可以进行优化
bw.write(this.jta.getText());
} catch (Exception e2) {
e2.printStackTrace();
}finally{
try {
bw.close();
fw.close();
} catch (Exception e3) {
 }
      }
    }
  }
}
1 0