1、implements Serializable 接口
public class Loan implements Serializable {
2、output 对象数组
Loan[] loans = new Loan[2];
loans[0] = new Loan(1.5, 4, 20000);
loans[1] = new Loan(1.5, 6, 20000);
output.writeObject(loans);
3、input newLoans
Loan[] newLoans = (Loan[]) (input.readObject());
for (int i = 0; i < newLoans.length; i++) {
System.out.println(newLoans[i].getTotalPayment());
}
示例
public class StorageLoan {
public static void main(String[] args) throws
ClassNotFoundException, IOException
{
try (ObjectOutputStream output = new ObjectOutputStream(
new FileOutputStream("Exercise06.dat")))
{
Loan[] loans = new Loan[2];
loans[0] = new Loan(1.5, 4, 20000);
loans[1] = new Loan(1.5, 6, 20000);
output.writeObject(loans);
}
try (ObjectInputStream input = new ObjectInputStream(
new FileInputStream("Exercise06.dat")))
{
while (true) {
Loan[] newLoans = (Loan[]) (input.readObject());
for (int i = 0; i < newLoans.length; i++) {
System.out.println(newLoans[i].getTotalPayment());
}
}
} catch (EOFException ex) {
System.out.println("all were read");
}
}
}