📄 randomaccessfiledemo.java
字号:
//随机文件读写演示
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class RandomAccessFileDemo extends JFrame implements ActionListener
{
JPanel pnlMain;
JLabel lblName,lblGender,lblAge,lblAddress;
JTextField txtName,txtGender,txtAge,txtAddress;
JButton btnLoad,btnSave;
JFileChooser fc;
RandomAccessFile rafUser;
//构造函数
public RandomAccessFileDemo()
{
super("随机文件读写演示");
fc=new JFileChooser();
pnlMain=new JPanel(new GridLayout(5,2));
lblName=new JLabel("姓名:");
lblGender=new JLabel("性别:");
lblAge=new JLabel("年龄:");
lblAddress=new JLabel("家庭地址:");
txtName=new JTextField(10);
txtGender=new JTextField(10);
txtAge=new JTextField(10);
txtAddress=new JTextField(10);
btnLoad=new JButton("读取");
btnLoad.addActionListener(this);
btnSave=new JButton("保存");
btnSave.addActionListener(this);
pnlMain.add(lblName);
pnlMain.add(txtName);
pnlMain.add(lblGender);
pnlMain.add(txtGender);
pnlMain.add(lblAge);
pnlMain.add(txtAge);
pnlMain.add(lblAddress);
pnlMain.add(txtAddress);
pnlMain.add(btnLoad);
pnlMain.add(btnSave);
setContentPane(pnlMain);
setSize(250,150);
setVisible(true);
}
//读取文件方法
public boolean loadFromFile()
{
try
{
//构造只读RandomAccessFile对象
rafUser=new RandomAccessFile("user.txt","r");
//文件指针定位到文件开始处
rafUser.seek(0);
//读取内容到相应组件中
txtName.setText(rafUser.readLine());
txtGender.setText(rafUser.readLine());
txtAge.setText(rafUser.readLine());
txtAddress.setText(rafUser.readLine());
//关闭文件
rafUser.close();
return true;
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"文件读取失败!");
//出现异常,返回False值
return false;
}
}
//保存文件方法
public boolean saveToFile()
{
try
{
//构造可读写RandomAccessFile对象
rafUser=new RandomAccessFile("user.txt","rw");
//文件指针定位到文件开始处
rafUser.seek(0);
//将组件中相应内容写入到文件
rafUser.writeBytes(txtName.getText()+"\r\n");
rafUser.writeBytes(txtGender.getText()+"\r\n");
rafUser.writeBytes(txtAge.getText()+"\r\n");
rafUser.writeBytes(txtAddress.getText());
rafUser.close();
return true;
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"文件保存失败!");
return false;
}
}
//按钮事件处理
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource()==btnSave)
if (saveToFile())
JOptionPane.showMessageDialog(null,"文件保存成功!");
if (ae.getSource()==btnLoad)
if (loadFromFile())
JOptionPane.showMessageDialog(null,"文件读取成功!");
}
public static void main(String args[])
{
new RandomAccessFileDemo();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -