📄 binaryio.java
字号:
//BinaryIO.java
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.awt.event.*;
public class BinaryIO extends JFrame implements ActionListener{
private JTextArea display=new JTextArea();
private JButton read=new JButton("从文件读记录"),
write=new JButton("产生随机记录");
private JTextField filename=new JTextField(10);
private JLabel prompt=new JLabel("文件名:",JLabel.RIGHT);
private JPanel commands=new JPanel();
public BinaryIO(){
super("BinaryIO");
read.addActionListener(this);
write.addActionListener(this);
commands.setLayout(new GridLayout(2,2,1,1));
commands.add(prompt);
commands.add(filename);
commands.add(read);
commands.add(write);
display.setLineWrap(true);
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add("North",commands);
this.getContentPane().add(new JScrollPane(display));
this.getContentPane().add("Center",display);
}
public void actionPerformed(ActionEvent e){
String fileName=filename.getText();
if(e.getSource()==read)
readRecords(fileName);
else
writeRecords(fileName);
}
private void readRecords(String filename){
try{
DataInputStream in=new DataInputStream(new FileInputStream(filename));
display.setText("Name Age pay\n");
try{
while(true){
String name=in.readUTF();
int age=in.readInt();
double pay=in.readDouble();
display.append(name+" "+age+" "+pay+"\n");
}
}catch(EOFException e){}
finally{in.close();
}
}catch(FileNotFoundException e){
display.setText("IOERROR: File not found:"+filename+"\n");
}catch(IOException e){
display.setText("IOERROR: "+e.getMessage()+"\n");
}
}
private void writeRecords(String filename){
try{
DataOutputStream out=new DataOutputStream(new FileOutputStream(filename));
for(int i=0;i<5;i++){
String name="Name"+i;
out.writeUTF("Name"+i);
out.writeInt((int)(20+Math.random()*25));
out.writeDouble(500.00+Math.random()*100);
}
out.close();
}catch(IOException e){
display.setText("IOERROR: "+e.getMessage()+"\n");
}
}
public static void main(String args[]){
BinaryIO bio=new BinaryIO();
bio.setSize(240,200);
bio.setVisible(true);
bio.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -