分类: Java
2021-05-24 17:33:23
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
public class GUIDemo extends JFrame{
private static final String TARGET_FILE = "./temp.txt";
//三个组件
private JButton saveButton;
private JButton loadButton;
private TextArea textArea;
//容器
private Container container;
//目标文件
private File targetFile;
public GUIDemo() throws IOException {
//设置title
super("File Demo");
//设置流布局
setLayout(new FlowLayout());
//获取容器
container = getContentPane();
//创建目标文件对象
targetFile = new File(TARGET_FILE);
if(targetFile.createNewFile()) {
System.out.println("文件不存在,货币代码创建成功");
}else {
System.out.println("文件存在");
}
//三个组件
textArea = new TextArea();
saveButton = new JButton("save");
loadButton = new JButton("load");
//保存文件按钮点击事件
saveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
//打开文件字符输出流
FileWriter writer = new FileWriter(targetFile);
//获取文本显示区文本
String result = textArea.getText();
//写入文件
writer.write(result);
//关闭输出流
writer.close();
//清空文本显示区内容
textArea.setText("");
System.out.println("存档成功");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
//读入文件按钮点击事件
loadButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
//字符读入流
FileReader reader = new FileReader(targetFile);
//读入缓冲区
char[] buffer = new char[1024];
//读入结果
StringBuffer result = new StringBuffer();
//每次读入缓冲区的长度
int len;
//从读入流中读取文件内容并形成结果
while((len = reader.read(buffer)) != -1) {
result.append(buffer,0,len);
}
//关闭读入流
reader.close();
//更新文本显示区内容
textArea.setText(result.toString());
System.out.println("读档成功");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
//装填三个组件
container.add(textArea);
container.add(loadButton);
container.add(saveButton);
//调整大小
setSize(500, 300);
//显示
setVisible(true);
}
public static void main(String[] args) throws IOException {
GUIDemo demo = new GUIDemo();
demo.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}