📄 readsequentialfile.java
字号:
// Fig. 15.6: ReadSequentialFile.java
// This program reads a file sequentially and displays each
// record in text fields.
import java.io.*;
import java.awt.*;
import java.awt.event.*;
public class ReadSequentialFile extends Frame
implements ActionListener {
// TextFields to display account number, first name,
// last name and balance.
private TextField accountField, firstNameField,
lastNameField, balanceField;
private Button next, // get next record in file
done; // quit program
// Application other pieces
private DataInputStream input;
// Constructor -- initialize the Frame
public ReadSequentialFile()
{
super( "Read Client File" );
// Open the file
try {
input = new DataInputStream(
new FileInputStream( "client.dat" ) );
}
catch ( IOException e ) {
System.err.println( "File not opened properly\n" +
e.toString() );
System.exit( 1 );
}
setSize( 300, 150 );
setLayout( new GridLayout( 5, 2 ) );
// create the components of the Frame
add( new Label( "Account Number" ) );
accountField = new TextField();
accountField.setEditable( false );
add( accountField );
add( new Label( "First Name" ) );
firstNameField = new TextField( 20 );
firstNameField.setEditable( false );
add( firstNameField );
add( new Label( "Last Name" ) );
lastNameField = new TextField( 20 );
lastNameField.setEditable( false );
add( lastNameField );
add( new Label( "Balance" ) );
balanceField = new TextField( 20 );
balanceField.setEditable( false );
add( balanceField );
next = new Button( "Next" );
next.addActionListener( this );
add( next );
done = new Button( "Done" );
done.addActionListener( this );
add( done );
setVisible( true );
}
public void actionPerformed( ActionEvent e )
{
if ( e.getSource() == next )
readRecord();
else
closeFile();
}
public void readRecord()
{
int account;
String first, last;
double balance;
// input the values from the file
try {
account = input.readInt();
first = input.readUTF();
last = input.readUTF();
balance = input.readDouble();
accountField.setText( String.valueOf( account ) );
firstNameField.setText( first );
lastNameField.setText( last );
balanceField.setText( String.valueOf( balance ) );
}
catch ( EOFException eof ) {
closeFile();
}
catch ( IOException e ) {
System.err.println( "Error during read from file\n" +
e.toString() );
System.exit( 1 );
}
}
private void closeFile()
{
try {
input.close();
System.exit( 0 );
}
catch ( IOException e ) {
System.err.println( "Error closing file\n" +
e.toString() );
System.exit( 1 );
}
}
public static void main( String args[] )
{
new ReadSequentialFile();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -