一、思路分析
1.记事本程序,简单的说,就是利用java中的输入,输出流,基于用户可视化界面来对文本文件进行操作。
2.可采用BufferedReader,BufferedWriter缓冲流,相比于字符流,字节流效率大大的提高。
二、实现过程
1.首先需要记事本的界面,用GUI组件实现记事本界面的开发。
用到的组件有:JMenuBar,JMenu,JMeunItem,JTextArea。
2.从硬盘中读取文本文件,需BufferedReader流,向硬盘中写入数据,需BufferedWriter流。
文件的读取和保存。可使用文件对话框JFileChooser来实现。
三、部分代码
界面部分:
public class Notepad extends JFrame implements ActionListener {
JMenuBar jbar; //菜单条
JMenu wj,bj,bz; //菜单
JMenuItem open,save,osave,exit,help,me; //菜单项
JTextArea jta; //文本区
public Notepad(){
jbar = new JMenuBar();
wj = new JMenu("文件");
bj = new JMenu("编辑");
bz = new JMenu("帮助");
jbar.add(wj);
jbar.add(bj);
jbar.add(bz);
setJMenuBar(jbar);
open = new JMenuItem("打开",new ImageIcon("img/dk.png"));
open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,InputEvent.CTRL_MASK)); //设置快捷键
wj.add(open);
open.addActionListener(this); //注册监听
open.setActionCommand("open");
wj.addSeparator();
save = new JMenuItem("保存");
wj.add(save);
save.addActionListener(this);
save.setActionCommand("save");
osave = new JMenuItem("另存为",new ImageIcon("img/bc.png"));
wj.add(osave);
osave.addActionListener(this);
osave.setActionCommand("osave");
wj.addSeparator();
exit = new JMenuItem("退出");
wj.add(exit);
exit.addActionListener(this);
exit.setActionCommand("exit");
help = new JMenuItem("查看帮助");
bz.add(help);
bz.addSeparator();
me = new JMenuItem("关于记事本");
bz.add(me);
jta = new JTextArea();
this.add(new JScrollPane(jta),BorderLayout.CENTER);
this.setVisible(true);
this.setSize(500,400);
this.setTitle("桃子记事本");
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
文件操作部分:
JFileChooser jfc = new JFileChooser();
jfc.setDialogTitle("请选择文件");
jfc.showOpenDialog(null);
jfc.setVisible(true);
String filepath = jfc.getSelectedFile().getAbsolutePath(); //获取文件的绝对路径
FileReader fr=null;
BufferedReader br=null;
try{
fr = new FileReader(filepath);
br = new BufferedReader(fr);
String s="";
String b="";
while((s=br.readLine())!=null){
b+=s+"\r\n";
}
jta.setText(b); //将读到的数据显示到JTextArea中
}catch(Exception e1){
e1.printStackTrace();
}finally{
try {
br.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
(主界面)
(文件对话框)
(读取文本文件)
>> 目前该记事本仅支持文本文件的读取与保存,在后续的版本中会增加复制,粘贴等功能。