涉及的知識點:GUI介面,IO操作,事件監聽。範例程式碼如下:
package ioTest;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileReader;import java.io.FileWriter;import javax.swing.ImageIcon;import javax.swing.JFileChooser;import javax.swing.JFrame;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JTextArea;public class NotePad extends JFrame implements ActionListener{JTextArea jta=null;JMenuBar jmb=null;JMenu jm=null;JMenuItem jmi=null;JMenuItem jmi2=null;public static void main(String[] args) {NotePad np=new NotePad();}public NotePad(){jta=new JTextArea();jmb=new JMenuBar();jm=new JMenu("檔案");jm.setMnemonic('f');//設定快速鍵jmi=new JMenuItem("開啟",new ImageIcon("D:\\javaSpace\\test_1\\src\\3.gif"));//註冊監聽jmi.addActionListener(this);jmi.setActionCommand("open");jmi2=new JMenuItem("儲存");jmi2.addActionListener(this);jmi2.setActionCommand("save");this.setJMenuBar(jmb);jmb.add(jm);jm.add(jmi);jm.add(jmi2);this.add(jta);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setSize(400,300);this.setVisible(true);}@Overridepublic void actionPerformed(ActionEvent arg0) {if(arg0.getActionCommand().equals("open")){//出現選擇檔案對話方塊JFileChooser jfc=new JFileChooser();jfc.setDialogTitle("請選擇檔案...");int value=jfc.showOpenDialog(null);//按預設顯示jfc.setVisible(true);if(value==JFileChooser.APPROVE_OPTION){String filename=jfc.getSelectedFile().getAbsolutePath();//System.out.println("test");FileReader fr=null;BufferedReader br=null;try{fr=new FileReader(filename);br=new BufferedReader(fr);String s,all = "";while((s=br.readLine())!=null){all+=s+"\r\n";}jta.setText(all);}catch(Exception e){e.printStackTrace();}finally{try {br.close();fr.close();} catch (Exception e2) {}}}else{//點JFileChooser關閉按扭時不做作務處理}}else if(arg0.getActionCommand().equals("save")){//出現儲存對話方塊JFileChooser jfc=new JFileChooser();jfc.setDialogTitle("另存新檔...");int value=jfc.showSaveDialog(null);jfc.setVisible(true);if(value==JFileChooser.APPROVE_OPTION){String filename=jfc.getSelectedFile().getAbsolutePath();FileWriter fw=null;BufferedWriter bw=null;try{fw=new FileWriter(filename);bw=new BufferedWriter(fw);bw.write(jta.getText());}catch(Exception e){e.printStackTrace();}finally{try {bw.close();fw.close();} catch (Exception e2) {}}}else{}}}}