java中输入输出的总括(初学必看) 4

xiaoxiao2022-06-12  38

import java.io.*; public class EditFile1 extends WindowAdapter implements ActionListener,TextListener { Frame f; TextArea ta1; Panel p1; TextField tf1; Button b1,b2,b3; FileDialog fd; File file1 = null; public static void main(String args[]) { (new EditFile1()).display(); } public void display() { f = new Frame("EditFile"); f.setSize(680,400); f.setLocation(200,140); f.setBackground(Color.lightGray); f.addWindowListener(this); tf1 = new TextField(); tf1.setEnabled(false); tf1.setFont(new Font("Dialog",0,20)); //设置文本行的初始字体 f.add(tf1,"North"); ta1 = new TextArea(); ta1.setFont(new Font("Dialog",0,20)); //设置文本区的初始字体 f.add(ta1); ta1.addTextListener(this); //注册文本区的事件监听程序 p1 = new Panel(); p1.setLayout(new FlowLayout(FlowLayout.LEFT)); b1 = new Button("Open"); b2 = new Button("Save"); b3 = new Button("Save As"); p1.add(b1); p1.add(b2); p1.add(b3); b2.setEnabled(false); b3.setEnabled(false); b1.addActionListener(this); //注册按钮的事件监听程序 b2.addActionListener(this); b3.addActionListener(this); f.add(p1,"South"); f.setVisible(true); } public void textValueChanged(TextEvent e) { //实现TextListener接口中的方法,对文本区操作时触发 b2.setEnabled(true); b3.setEnabled(true); } public void actionPerformed(ActionEvent e) { if (e.getSource()==b1) //单击[打开]按钮时 { fd = new FileDialog(f,"Open",FileDialog.LOAD); fd.setVisible(true); //创建并显示打开文件对话框 if ((fd.getDirectory()!=null) && (fd.getFile()!=null)) { tf1.setText(fd.getDirectory()+fd.getFile()); try //以缓冲区方式读取文件内容 { file1 = new File(fd.getDirectory(),fd.getFile()); FileReader fr = new FileReader(file1); BufferedReader br = new BufferedReader(fr); String aline; while ((aline=br.readLine()) != null)//按行读取文本 ta1.append(aline+"\r\n"); fr.close(); br.close(); } catch (IOException ioe) { System.out.println(ioe); } } } if ((e.getSource()==b2) || (e.getSource()==b3)) { //单击[保存]按钮时 if ((e.getSource()==b3) ||(e.getSource()==b2)&&(file1==null)) { //单击[SaveAs]按钮时,或单击[Save]按钮且文件对象为空时 fd = new FileDialog(f,"Save",FileDialog.SAVE); if (file1==null) fd.setFile("Edit1.txt"); else fd.setFile(file1.getName()); fd.setVisible(true); //创建并显示保存文件对话框 if ((fd.getDirectory()!=null) && (fd.getFile()!=null)) { tf1.setText(fd.getDirectory()+fd.getFile()); file1 = new File(fd.getDirectory(),fd.getFile()); save(file1); } } else save(file1); } } public void save(File file1) { try //将文本区内容写入字符输出流 { FileWriter fw = new FileWriter(file1); fw.write(ta1.getText()); fw.close(); b2.setEnabled(false); b3.setEnabled(false); } catch (IOException ioe) { System.out.println(ioe); } } public void windowClosing(WindowEvent e) { System.exit(0); } } 相关资源:Java 面经手册·小傅哥(公众号:bugstack虫洞栈).pdf
转载请注明原文地址: https://www.6miu.com/read-4933028.html

最新回复(0)