/**
* 读取文本文件
* JavaAlpha
*/
import java.io.*;
import java.awt.*;
import java.awt.event.*;
public class jtxtfm {
public static void main(String args[]) {
jtxtfrm fm = new jtxtfrm(); //这里是程序开始执行的地方,新建一个窗口
}
}
class jtxtfrm extends Frame implements ActionListener {
FileDialog op, sv;//文件对话框
Button btn1, btn2, btn3;//按钮
TextArea tarea;//文本框
jtxtfrm() {
super("读写文件");//标题
setLayout(null);//布局
setBackground(Color.cyan);//背景色
setSize(600, 300);//设置大学
setVisible(true);//设置可见
btn1 = new Button("打开");//创建按钮
btn2 = new Button("保存");
btn3 = new Button("关闭");
tarea = new TextArea("");//创建文本框
add(btn1);//添加按钮
add(btn2);
add(btn3);
add(tarea);
tarea.setBounds(30, 50, 460, 220);//设置文本框位置
btn1.setBounds(520, 60, 50, 30);
btn2.setBounds(520, 120, 50, 30);
btn3.setBounds(520, 180, 50, 30);
op = new FileDialog(this, "打开", FileDialog.LOAD);//新建对话框
sv = new FileDialog(this, "保存", FileDialog.SAVE);
btn1.addActionListener(this);//设置按钮点击监听事件
btn2.addActionListener(this);
btn3.addActionListener(this);
addWindowListener(new WindowAdapter() {//关闭事件处理
public void windowClosing(WindowEvent e) {
setVisible(false);//设置不可见
System.exit(0);//程序关闭
}
});
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btn1) {//按钮1事件处理
String str;
op.setVisible(true);//设置可见
try {
File f1 = new File(op.getDirectory(), op.getFile());//打开文件
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);//读取文件
tarea.setText("");//设置文本框内容为空
while ((str = br.readLine()) != null)
tarea.append(str + '\n');//文本框添加读取的文件内容
fr.close();//关闭读取
} catch (Exception e1) {//如果有错误,这里进行处理
e1.printStackTrace();//打印错误信息
}
}
if (e.getSource() == btn2) {//按钮1事件处理
sv.setVisible(true);
try {
File f1 = new File(sv.getDirectory(), sv.getFile());
FileWriter fw = new FileWriter(f1);
BufferedWriter bw = new BufferedWriter(fw);
String gt = tarea.getText();//获取文本框内容
bw.write(gt, 0, gt.length());//将文本框内容写入文件
bw.flush();//真正的写入文件
fw.close();//关闭写入
} catch (Exception e2) {//错误处理
e2.printStackTrace();//打印错误信息
}
}
if (e.getSource() == btn3) {//按钮3事件处理
System.exit(0);//关闭程序
}
}
}
Java Frame 窗口读取 文本文件代码
最新推荐文章于 2021-02-13 17:21:44 发布