学习笔记三十一:IO流(三)

活鱼会逆流而上,死鱼才会随波逐流。


本讲内容:文件流


例一:写一个记事本

package b;

import java.io.*;
import java.awt.*;
import javax.swing.*;

import java.awt.event.*;

public class NotePad extends JFrame implements ActionListener{
	JTextArea wby;
	JScrollPane gd;
	JMenuBar cd;
	JMenu cd1;
	JMenuItem ycd1,ycd2;
	public static void main(String[] args) {
		NotePad np=new NotePad();
		
	}
	
	public NotePad() {
		wby=new JTextArea();
		gd=new JScrollPane(wby);
		cd=new JMenuBar();
		cd1=new JMenu("文件(F)");
		cd1.setMnemonic('F');
		ycd1=new JMenuItem("打开",new ImageIcon("images/1.gif"));
		//对打开按钮注册监听
		ycd1.addActionListener(this);
		ycd1.setActionCommand("open");
		
		ycd2=new JMenuItem("保存",new ImageIcon("images/3.gif"));
		//对保存按钮做监听
		ycd2.addActionListener(this);
		ycd2.setActionCommand("save");
		
		cd1.add(ycd1); cd1.add(ycd2);
		cd.add(cd1);
		this.setJMenuBar(cd);
		
		this.add(gd);
		
		// 设置窗体属性  
        this.setTitle("迷你版记事本—小劲");  
        this.setLocation(300, 300);  
        this.setSize(500, 400);  
        this.setVisible(true);  
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
	}

	public void actionPerformed(ActionEvent e) {
		if(e.getActionCommand().equals("open")){
			//文件选择组件
			JFileChooser fch=new JFileChooser();
			//设置标题
			fch.setDialogTitle("请选择文件");
			//(null是打开的时候使用窗口默认的方式)
			fch.showOpenDialog(null);
			//使该组件可见
			fch.setVisible(true);
			
			//得到用户选中的文件全路径
			String filename=fch.getSelectedFile().getAbsolutePath();
			
			FileReader fr=null;
			BufferedReader br=null;
			
			try {
				fr=new FileReader(filename);
				br=new BufferedReader(fr);
				
				//从文件中读取信息并显示文本域中
				String s="";
				String all="";
				while((s=br.readLine())!=null){
					all+=s+"\r\n";
				}
				wby.setText(all);//放置到wby即可
			} catch (Exception e1) {
				e1.printStackTrace();
			}finally{
				try {
					br.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}else if(e.getActionCommand().equals("save")){
			JFileChooser fch=new JFileChooser();
			fch.setDialogTitle("另存为");
			fch.showSaveDialog(null);
			fch.setVisible(true);
			
			//用户希望把文件保存到何处,文件的全路径
			String file=fch.getSelectedFile().getAbsolutePath();
			//准备写入到指定文件
			FileWriter fw=null;
			BufferedWriter bw=null;
			try {
				fw=new FileWriter(file);
				bw=new BufferedWriter(fw);
				bw.write(this.wby.getText());
			} catch (IOException e1) {
				e1.printStackTrace();
			}finally{
				try {
					bw.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	}
}



本讲就到这里,Take your time and enjoy it

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值