java学习之io编程(记事本功能实现)


一个简单的不能再简单的记事本,仅拥有打开,保存的功能,不是很完美。。。。。
package com.test;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;

import javax.swing.*;


public class Txt extends JFrame implements ActionListener{

	JTextArea jta = null;
	JMenuBar jmb = null;
	JMenu jm= null;
	JMenuItem jmi1 = null;
	JMenuItem jmi2 = null;
	
	public Txt(){
		jta = new JTextArea();
		jmb = new JMenuBar();
		jm = new JMenu("文件");
		jmi1 = new JMenuItem("打开");
		jmi1.addActionListener(this);
		jmi1.setActionCommand("open");
		
		jmi2 = new JMenuItem("保存");
		jmi2.addActionListener(this);
		jmi2.setActionCommand("save");
		
		this.setJMenuBar(jmb);//在最上面放入MenuBar组件
		this.add(jta);
		
		jmb.add(jm);
		jm.add(jmi1);
		jm.add(jmi2);
		
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setSize(300,400);
		this.setVisible(true);
	}
	
	
	
	public void actionPerformed(ActionEvent e) {
		//判断与哪个选项被选中
		if(e.getActionCommand().equals("open")){
			//JFileChooser组件 *………………*
			JFileChooser jfc = new JFileChooser();
			//设置名字
			jfc.setDialogTitle("请选择文件");
			//ShowOpenDialog打开某文件的对话框  null代表默认位置
			//ShowSaveDialog存储某文件的对话框
			jfc.showOpenDialog(null);
			jfc.setVisible(true);
			
			//得到要打开文件的路径
			String FilePath = jfc.getSelectedFile().getAbsolutePath();
			FileReader fr = null;
			BufferedReader br = null;
			
			try {
				fr = new FileReader(FilePath);
				br = new BufferedReader(fr);
				
				
				String s = "";
				String all = "";
				while((s=br.readLine())!=null){
					
					all+=s+"\r\n";
				}
				jta.setText(all);
					
			} catch (FileNotFoundException e1) {
				
				e1.printStackTrace();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}finally{
				try {
					br.close();
					fr.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}		
		}
		
		
		else if(e.getActionCommand().equals("save")){
			JFileChooser jfc1 = new JFileChooser();
			jfc1.setDialogTitle("另存为");
			jfc1.showSaveDialog(null);
			jfc1.setVisible(true);
			
			String path = jfc1.getSelectedFile().getAbsolutePath();
			
			FileWriter fw = null;
			BufferedWriter bw = null;
			
			try {
				fw = new FileWriter(path);
				bw = new BufferedWriter(fw);
				
				bw.write(this.jta.getText());
			} catch (IOException e1) {
				e1.printStackTrace();
			}finally{
				try {
					bw.close();
					fw.close();				
				} catch (IOException e1) {

				}
				
			}
			
		}
		
	}
	
	public static void main(String[] args) {
		new Txt();
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值