package
com.hz.FileandIO;

import
java.awt.BorderLayout;
import
java.awt.GridLayout;

import
javax.swing.JButton;
import
javax.swing.JLabel;
import
javax.swing.JPanel;
import
javax.swing.JTextField;


public
class
BankUI
extends
JPanel
...
{

protected final static String names[] = ...{"Account number","First name","Last name","Balance","Transaction Amount" };
protected JLabel labels[];
protected JTextField fields[];
protected JButton doTask1,doTask2;
protected JPanel innerPanelCenter,innerPanelSouth;
protected int size;
public static final int ACCOUNT = 0,FIRSTNAME = 1, LASTNAME =2,BALANCE=3,TRANSACTION=4;
public BankUI(int mySize)

...{
size = mySize;
labels = new JLabel[size];
fields = new JTextField[size];
for(int i=0;i<labels.length;i++)
labels[i] = new JLabel(names[i]);
for(int i=0;i<fields.length;i++)
fields[i] = new JTextField();
innerPanelCenter = new JPanel();
innerPanelCenter.setLayout(new GridLayout(size,2));

for(int i=0;i<size;i++)...{
innerPanelCenter.add(labels[i]);
innerPanelCenter.add(fields[i]);
}
doTask1 =new JButton();
doTask2 = new JButton();
innerPanelSouth = new JPanel();
innerPanelSouth.add(doTask1);
innerPanelSouth.add(doTask2);
setLayout(new BorderLayout());
add(innerPanelCenter,BorderLayout.CENTER);
add(innerPanelSouth,BorderLayout.SOUTH);
validate();
}

public JButton getDoTask1Button()...{
return doTask1;
}

public JButton getDoTask2Button()...{
return doTask2;
}

public JTextField[] getFields()...{
return fields;
}

public void clearFields()...{
for(int i=0;i<size;i++)
fields[i].setText("");
}

public void setFieldValues(String strings[])throws IllegalArgumentException...{
if(strings.length != size)
throw new IllegalArgumentException("There must be" +
size + "Strings in the array");
for(int i=0;i<size;i++)
fields[i].setText(strings[i]);
}

public String[] getFieldValues()...{
String values[] = new String[size];
for(int i=0;i<size;i++)
values[i] = fields[i].getText();
return values;
}
}
BankUI包含一个可以在多个程序中重用的GUI
package
com.hz.FileandIO;

//
AccountRecord方法主要是维护一个帐号的信息。
import
java.io.Serializable;
//
Serializable是一个标记接口。(标记接口不含任何方法)实现该接口能使ObjectOutputStream和
//
ObjectInputStream使用AccountRecord对象。

public
class
AccountRecord
implements
Serializable
...
{

private int account;
private String firstName;
private String lastName;
private double balance;
public AccountRecord()

...{
this(0,"","",0.0);
}


public AccountRecord(int acct, String first, String last, double bal) ...{
// TODO 自动生成构造函数存根
setAccount(acct);
setFirstName(first);
setFirstName(last);
setBalance(bal);
}


public int getAccount() ...{
return account;
}


public void setAccount(int account) ...{
this.account = account;
}


public String getFirstName() ...{
return firstName;
}


public void setFirstName(String firstName) ...{
this.firstName = firstName;
}


public String getLastName() ...{
return lastName;
}


public void setLastName(String lastName) ...{
this.lastName = lastName;
}


public double getBalance() ...{
return balance;
}


public void setBalance(double balance) ...{
this.balance = balance;
}

}
AccountRecord此类主要是维护一个帐号的信息
package
com.hz.FileandIO;


//
创建顺序存取文件
import
java.awt.BorderLayout;
import
java.awt.event.ActionEvent;
import
java.awt.event.ActionListener;
import
java.awt.event.WindowAdapter;
import
java.awt.event.WindowEvent;
import
java.io.File;
import
java.io.FileNotFoundException;
import
java.io.FileOutputStream;
import
java.io.IOException;
import
java.io.ObjectOutputStream;

import
javax.swing.JButton;
import
javax.swing.JFileChooser;
import
javax.swing.JFrame;
import
javax.swing.JOptionPane;


public
class
CreateSequentialFile
extends
JFrame
...
{

private ObjectOutputStream output;
private BankUI userInterface;
private JButton enterButton,openButton;
public CreateSequentialFile()

...{
super("Creating a Swquential File of Objects");
userInterface = new BankUI(4);
getContentPane().add(userInterface,BorderLayout.CENTER);
openButton = userInterface.getDoTask1Button();
openButton.setText("保存文件!!");
openButton.addActionListener(

new ActionListener()...{
public void actionPerformed(ActionEvent event)

...{
openFile();
}
}
);
enterButton = userInterface.getDoTask2Button();
enterButton.setText("Enter");
enterButton.setEnabled(false);
enterButton.addActionListener(

new ActionListener()...{
public void actionPerformed(ActionEvent event)

...{
addRecord();
}
}
);
addWindowListener(

new WindowAdapter()...{
public void windowClosing(WindowEvent event)

...{
if(output != null)
addRecord();
closeFile();
}
}
);
setSize(300,200);
setVisible(true);
}
private void openFile()

...{
//创建了一个fileChooser对象
JFileChooser fileChooser = new JFileChooser();
//调用serFileSelectionMode方法以指定用户是否可以从fileChooser中选择文件目录。
//JFileCooser类的静态常量FILES_ONLY,指出用户只能选择文件。
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

/**//*调用fileChooser中的showOpenDialog方法来显示标题为“save”的JFileChooser对话框。
this指定JfileChooser对话框的父窗口确定屏幕上的显示位置
*/
int result = fileChooser.showOpenDialog(this);
//通过比较result和静态常量CANCEL_OPTION,来判断用户是否单击了“Cancel”按钮。
if(result == JFileChooser.CANCEL_OPTION)
return;
//getSwlectedFile()方法来获得用户所选择的文件。
File fileName = fileChooser.getSelectedFile();
if(fileName == null || fileName.getName().equals(""))
JOptionPane.showMessageDialog(this,"Invalid File Name",
"Invalid File Name",JOptionPane.ERROR_MESSAGE);

else...{

try ...{
//输出文件
FileOutputStream fos = new FileOutputStream(fileName);
output = new ObjectOutputStream(fos);
openButton.setEnabled(false);
enterButton.setEnabled(true);

} catch (FileNotFoundException e) ...{
// TODO 自动生成 catch 块
e.printStackTrace();

} catch (IOException e) ...{
// TODO 自动生成 catch 块
JOptionPane.showMessageDialog(this, "Error Opening file",
"Error",JOptionPane.ERROR_MESSAGE);
}
}
}
private void closeFile()

...{

try ...{
output.close();
System.exit(0);

} catch (IOException ioException) ...{
// TODO 自动生成 catch 块
JOptionPane.showMessageDialog(this, "Error closing file",
"Error",JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
}
private void addRecord()

...{
int accountNumber = 0;
AccountRecord record;
String fieldValues[] = userInterface.getFieldValues();
if( ! fieldValues[BankUI.ACCOUNT].equals(""))

...{

try...{
accountNumber = Integer.parseInt(fieldValues[BankUI.ACCOUNT]);
if(accountNumber > 0)

...{
record = new AccountRecord(accountNumber,fieldValues[BankUI.FIRSTNAME],fieldValues[BankUI.LASTNAME],Double.parseDouble(fieldValues[BankUI.BALANCE]));
output.writeObject(record);
output.flush();
}
else

...{
JOptionPane.showMessageDialog(this, "Account number must be greater than 0","Bad accountnumber",JOptionPane.ERROR_MESSAGE);
}
userInterface.clearFields();

}catch(NumberFormatException formatException)...{
JOptionPane.showMessageDialog(this, "Bad account number or balance","Invalid Number Format",JOptionPane.ERROR_MESSAGE);

}catch(IOException io)...{
JOptionPane.showConfirmDialog(this, "Error writing to file","IO exception",JOptionPane.ERROR_MESSAGE);
closeFile();
}
}
}

public static void main(String args[])...{
new CreateSequentialFile();
}
}
使用ObjectOutputStream创建顺序文件