package hxy.widget.com; import java.awt.*; import java.awt.event.*; import java.io.*; import javax.swing.JFrame; public class AboutDialog extends JFrame implements ActionListener { /** * */ private static final long serialVersionUID = 5210678447574536145L; private FileDialog filedialog_save, filedialog_load; private MenuBar menubar;//菜单栏 private Menu menu;//菜单 private MenuItem itemOpen, itemSave;//菜单项 private TextArea text;//文本域 private BufferedReader in;//从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。 private FileReader file_reader;//用于读取字符流。要读取原始字节流,请考虑使用 FileInputStream private BufferedWriter out;//将文本写入字符输出流,缓冲各个字符,从而提供单个字符、数组和字符串的高效写入。 private FileWriter file_writer;//用来写入字符文件的便捷类 public AboutDialog() { super("打开/保存"); setSize(800, 600); setVisible(true); menubar = new MenuBar(); menu = new Menu("文件"); itemOpen = new MenuItem("打开文件"); itemSave = new MenuItem("保存文件"); itemOpen.addActionListener(this); itemSave.addActionListener(this); menu.add(itemOpen); menu.add(itemSave); menubar.add(menu); setMenuBar(menubar); filedialog_save = new FileDialog(this, "保存文件", FileDialog.SAVE); filedialog_load = new FileDialog(this, "打开文件", FileDialog.LOAD); filedialog_save.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { filedialog_save.setVisible(false); } }); filedialog_load.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { filedialog_load.setVisible(false); } }); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); text = new TextArea("文本域。。"); add(text, BorderLayout.CENTER); } public void actionPerformed(ActionEvent e) { if (e.getSource() == itemOpen) { filedialog_load.setVisible(true); text.setText(null);//清除文本域 String s; if (filedialog_load.getFile() != null) { try { File file = new File(filedialog_load.getDirectory(), filedialog_load.getFile());//获得所打开的文件 file_reader = new FileReader(file); in = new BufferedReader(file_reader); while ((s = in.readLine()) != null) {//readLine()读取一个文本行 text.append(s + '\n');//别忘了换行符 } in.close();//关闭该流并释放与之关联的所有资源。 file_reader.close();//关闭该流并释放与之关联的所有资源 ,FileReader中的close()继承自InputStreamReader } catch (IOException e2) { } } } else if (e.getSource() == itemSave) { filedialog_save.setVisible(true); if (filedialog_save.getFile() != null) { System.out.print(filedialog_save.getFile()); try { File file = new File(filedialog_save.getDirectory(), filedialog_save.getFile());//获得要保存的文件 file_writer = new FileWriter(file); out = new BufferedWriter(file_writer); /* * public void write(String s, * int off, * int len) * throws IOException * ------------------------- * s - 要写入的字符串 * off - 开始读取字符处的偏移量 * len - 要写入的字符数 * */ out.write(text.getText(), 0, (text.getText()).length()); out.close();//关闭该流并释放与之关联的所有资源。 file_writer.close();//关闭该流并释放与之关联的所有资源。 } catch (IOException e2) { } } } } public static void main(String args[]) { new AboutDialog(); } }