java 记事本 io流的应用

来源:互联网 发布:水果机辅助软件助手 编辑:程序博客网 时间:2024/05/18 14:45

这是个我做的一个io流的练习,界面采用了java swing,其中主要的控件为JFileChooser,实例化该控件并调用showSaveDialog或者showOpenDialog分别显示存储和保存的界面。具体用法可以查询参考文档。


窗体的swing部分,构建了整个程序的外部框架,包含工具栏等

package notePad;import java.awt.BorderLayout;import java.awt.Event;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowEvent;import java.awt.event.WindowListener;import javax.swing.JFrame;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JOptionPane;import javax.swing.JScrollPane;import javax.swing.JTextArea;import javax.swing.KeyStroke;public class NotePadSwing extends JFrame implements ActionListener,WindowListener {private static final long serialVersionUID = 1L;JMenuBar jmb = new JMenuBar();JMenu jm1 = new JMenu("文件(F)");JMenu jm2 = new JMenu("帮助(H)");JMenuItem jmi1 = new JMenuItem("新建(N)");JMenuItem jmi2 = new JMenuItem("打开(O)");JMenuItem jmi3 = new JMenuItem("保存(S)");JMenuItem jmi4 = new JMenuItem("另存(A)");JMenuItem jmi5 = new JMenuItem("关于记事本(A)");JTextArea jta = new JTextArea();JScrollPane jsp=new JScrollPane( jta);//给控件设置快捷键,并添加到窗体中NotePadSwing() {jm1.setMnemonic('F');jm2.setMnemonic('H');jmi1.addActionListener(this);jmi1.setAccelerator(KeyStroke.getKeyStroke('N',Event.CTRL_MASK,false));jmi1.setMnemonic('N');jmi2.addActionListener(this);jmi2.setAccelerator(KeyStroke.getKeyStroke('O',Event.CTRL_MASK,false));jmi2.setMnemonic('O');jmi3.addActionListener(this);jmi3.setAccelerator(KeyStroke.getKeyStroke('S',Event.CTRL_MASK,false));jmi3.setMnemonic('S');jmi4.addActionListener(this);jmi4.setAccelerator(KeyStroke.getKeyStroke('A',Event.CTRL_MASK,false));jmi4.setMnemonic('A');jmi5.addActionListener(this);jmi5.setAccelerator(KeyStroke.getKeyStroke('A',Event.CTRL_MASK,false));jmi5.setMnemonic('A');jmb.add(jm1);jmb.add(jm2);jm1.add(jmi1);jm1.add(jmi2);jm1.add(jmi3);jm1.add(jmi4);jm2.add(jmi5);jta.setLineWrap(true);//设置布局this.addWindowListener(this);this.add(jmb,BorderLayout.NORTH);this.add(jsp,BorderLayout.CENTER);this.setBounds(300, 300, 500, 700);this.setTitle("记事本");this.setVisible(true);this.setDefaultCloseOperation(3);}/** * 触发事件时的处理方法 */public void actionPerformed(ActionEvent e) {if (e.getSource() == jmi1) {NotePadOperator.newfile(jta,this);} else if (e.getSource() == jmi2) {NotePadOperator.open(jta, this);} else if (e.getSource() == jmi3) {NotePadOperator.save(jta, this);} else if (e.getSource() == jmi4) {NotePadOperator.saveAs(jta, this);} else if (e.getSource() == jmi5) {JOptionPane.showMessageDialog(this, "作者:xx   版本号:1.0");}}/** * 当未保存时,关闭窗口弹出提示框 */public void windowClosing(WindowEvent arg0) {NotePadOperator.closesave(jta,this);}//下面的方法由于没有使用,所以不用添加内容@Overridepublic void windowClosed(WindowEvent arg0) {// TODO Auto-generated method stub}public void windowDeactivated(WindowEvent arg0) {// TODO Auto-generated method stub}public void windowDeiconified(WindowEvent arg0) {// TODO Auto-generated method stub}public void windowIconified(WindowEvent arg0) {// TODO Auto-generated method stub}public void windowOpened(WindowEvent arg0) {// TODO Auto-generated method stub}public void windowActivated(WindowEvent arg0) {// TODO Auto-generated method stub}}

主要的操作部分,包含了保存的方法和打开的方法,采用io流实现。

package notePad;import java.io.File;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import javax.swing.JFileChooser;import javax.swing.JOptionPane;import javax.swing.JTextArea;public class NotePadOperator {// 用来保存打开一个文件后,该文件的地址,用于保存方法private static String openPath = null;// 用来表示一个文件是否进行了存储操作private static String inner = null;/** * 另存为的方法 * * @param jta *            文本域组建对象 * @param jsb *            swing窗体对象 */public static void saveAs(JTextArea jta, NotePadSwing jsb) {JFileChooser jfc = new JFileChooser(".");jfc.setAcceptAllFileFilterUsed(false);jfc.addChoosableFileFilter(new NotPadFlieFilter("txt"));if (jfc.showSaveDialog(jsb) == JFileChooser.APPROVE_OPTION) {String description = jfc.getFileFilter().getDescription();String ext = description.substring(description.lastIndexOf("."),description.length() - 1);String filename = jfc.getSelectedFile().getName();String path = null;if (jfc.getSelectedFile().exists()) {int copy = JOptionPane.showConfirmDialog(null, "是否要覆盖当前文件?","保存", JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);if (copy == JOptionPane.YES_OPTION) {jfc.approveSelection();} elsesaveAs(jta, jsb);}try {if (filename.substring(filename.lastIndexOf("."),filename.length()).equals(ext)) {path = jfc.getSelectedFile().getAbsolutePath();}else{path = jfc.getSelectedFile().getAbsolutePath() + ext;}} catch (StringIndexOutOfBoundsException e) {path = jfc.getSelectedFile().getAbsolutePath() + ext;}File f = new File(path);FileWriter fw = null;try {fw = new FileWriter(f);String output = jta.getText();//char[] chars = output.toCharArray();//fw.write(chars, 0, chars.length);fw.write(output);} catch (IOException e) {e.printStackTrace();} finally {if (fw != null)try {fw.close();} catch (IOException e) {e.printStackTrace();}}}}/** * 保存的方法 * * @param jta *            文本域组件对象 * @param jsb *            swing窗体对象 */public static void save(JTextArea jta, NotePadSwing jsb) {if (openPath != null) {File f = new File(openPath);FileWriter fw = null;try {fw = new FileWriter(f);String output = jta.getText();char[] chars = output.toCharArray();fw.write(chars, 0, chars.length);inner=jta.getText();} catch (IOException e) {e.printStackTrace();} finally {if (fw != null)try {fw.close();} catch (IOException e) {e.printStackTrace();}}} else {saveAs(jta, jsb);}}/** * 打开文件的方法 * * @param jta *            文本域组件对象 * @param jsb *            swing窗体对象 */public static void open(JTextArea jta, NotePadSwing jsb) {JFileChooser jfc = new JFileChooser(".");jfc.setAcceptAllFileFilterUsed(false);jfc.addChoosableFileFilter(new NotPadFlieFilter("txt"));if (jfc.showOpenDialog(jsb) == JFileChooser.APPROVE_OPTION) {jsb.setTitle(jfc.getSelectedFile().getName()+"-记事本");File f = new File(jfc.getSelectedFile().getPath());openPath = jfc.getSelectedFile().getPath();FileReader fr = null;StringBuffer s = new StringBuffer("");try {fr = new FileReader(f);char[] chars = new char[1024];int n = 0;while ((n = fr.read(chars)) != -1) {s.append(chars, 0, n);}String input = s.toString();jta.setText(input);inner=jta.getText();} catch (IOException e) {e.printStackTrace();} finally {if (fr != null)try {fr.close();} catch (IOException e) {e.printStackTrace();}}}}/** * 新建文件方法 * * @param jta *            文本域组件对象 */public static void newfile(JTextArea jta, NotePadSwing jsb) {jsb.setTitle("记事本");if(!jta.getText().equals(inner)){int copy = JOptionPane.showConfirmDialog(null, "当前文件没有保存,是否保存","记事本",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE);if(copy==JOptionPane.YES_OPTION){save(jta,jsb);}else if(copy==JOptionPane.NO_OPTION){jta.setText(null);        inner=null;}else {}}else{jta.setText(null);        inner=null;}}/** 关闭时如果内容改变而没有储存时的方法 * * @param jta *            文本域组件对象 * @param jsb *            swing窗体对象 */public static void closesave(JTextArea jta, NotePadSwing jsb){if(!jta.getText().equals(inner)){int copy = JOptionPane.showConfirmDialog(null, "当前文件没有保存,是否保存","记事本",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE);if(copy==JOptionPane.YES_OPTION){save(jta,jsb);}else if(copy==JOptionPane.NO_OPTION){jsb.setDefaultCloseOperation(3);}else {jsb.setDefaultCloseOperation(0);}}else{jsb.setDefaultCloseOperation(3);}}}

自定义的一个文件过滤器

package notePad;import java.io.File;import javax.swing.filechooser.FileFilter;public class NotPadFlieFilter extends FileFilter {String ext;/** * 构造方法,传入后缀名 *  * @param ext *            后缀 */public NotPadFlieFilter(String ext) {this.ext = ext;}/** * 重写FileFilter中的方法,用来设置过滤条件 */public boolean accept(File f) {if (f.isDirectory()) {return true;}String fileName = f.getName();int index = fileName.lastIndexOf('.');if (index > 0 && index < fileName.length() - 1) {String extension = fileName.substring(index + 1).toLowerCase();if (extension.equals(ext))return true;}return false;}/** * 重写FileFilter中的方法,用来说明后缀名 */public String getDescription() {if (ext.equals("txt")) {return "文本文件(*.txt)";}return null;}}


最后的包含main方法的类

package notePad;public class NotePadDemo {public static void main(String[] args) {new NotePadSwing();}}

整个程序由于还是初学者,很多地方写的不够好,需要改进

原创粉丝点击