java利⽤Swing和IO流实现记事本保存和读取⽂件需求:⽤swing编写⼀个简易的记事本界⾯
⽤IO流完成保存⽂件和读取⽂件的操作
package Chapter06;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
/**
* 需求:实现简易记事本读取⽂件保存⽂件的简单操作
* @author:mg
*/
public class Notepad extends JFrame implements ActionListener {
//创建组件
JMenu jm1;
JMenuBar jmb1;
JTextArea jta;
JMenuItem jmi1;
JMenuItem jmi2;
//构造⽅法实现界⾯⽣成
public Notepad(){
//创建jtajavaswing实现购买
jta = new JTextArea();
jmb1 = new JMenuBar();
this.add(jta);
jm1 = new JMenu("⽂件");
this.setJMenuBar(jmb1);
jmb1.add(jm1);
jmi1 = new JMenuItem("打开⽂件");
jmi1.setActionCommand("open");
jmi1.addActionListener(this);
jmi2 = new JMenuItem("保存⽂件");
jmi2.setActionCommand("save");
jmi2.addActionListener(this);
jm1.add(jmi1);
jm1.add(jmi2);
this.setTitle("记事本");
this.setSize(600,400);
this.setLocation(400,300);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//本类进⾏事件处理
@Override
public void actionPerformed(ActionEvent e){
ActionCommand().equals("save")){
String filename = "D:\\IDEA代码\\Home_Work\\src\\Chapter06\\a.txt";
FileWriter fw = null;
BufferedWriter bw = null;
try{
fw = new FileWriter(filename);
bw = new BufferedWriter(fw);
String str = Text();
bw.write(Text());
System.out.println("写⼊⽂件成功!");
}catch(Exception e1){
e1.printStackTrace();
}finally {
try{
bw.close();
fw.close();
}catch (IOException e2){
e2.printStackTrace();
}
}
}else ActionCommand().equals("open")){
String filename = "D:\\IDEA代码\\Home_Work\\src\\Chapter06\\a.txt"; FileReader fr = null;
BufferedReader br = null;
try{
fr = new FileReader(filename);
br = new BufferedReader(fr);
String line = null;
String add = "";
while((line = br.readLine())!=null){
add += line + "\n";
}
this.jta.setText(add);
System.out.println("读取⽂件成功!");
}catch (IOException e1){
e1.printStackTrace();
}finally {
try{
br.close();
fr.close();
}catch(IOException e2){
e2.printStackTrace();
}
}
}
}
}
package Chapter06;
//测试类
public class Test {
public static void main(String[] args) {
Notepad np = new Notepad();
}
}
代码敲的不容易,给个三连再⾛吧!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论