Serializable 接口是启用其序列化功能的接口~写完17.6发现17.7和17.6是一个类型的索性写在一起也方便检验~~
实现代码:
package CJF;
import java.io.*;
import java.util.Date;
public class Loan implements Serializable {
private double a;
private int n;
private double lo;
private Date d;
public Loan(){
this(2.5,1,100);
}
public Loan(double a, int n, double lo) {
this.a = a;
this.n = n;
this.lo = lo;
d = new java.util.Date();
}
public double getA(){
return a;
}
public void setA(double a){
this.a = a;
}
public int getN(){
return n;
}
public void getN(int n){
this.n = n;
}
public double getlo(){
return lo;
}
public void setlo(int lo){
this.lo = lo;
}
public double getM(){
double m = a / 1200;
double m1 = lo * m / (1 - (1 / Math.pow(1 + m,n * 12)));
return m1;
}
public double getT(){
double t = getM() * n * 12;
return t;
}
public java.util.Date getD(){
return d;
}
public static void main(String[] args){ // 17.6
Loan lo1 = new Loan(2.5,2,500);
Loan lo2 = new Loan(3.6,3,100);
Loan lo3 = new Loan(4.7,4,200);
Loan lo4 = new Loan(5.8,5,300);
Loan lo5 = new Loan(6.5,6,100);
try{
FileOutputStream fs = new FileOutputStream("f.dat");
ObjectOutputStream os = new ObjectOutputStream(fs); // 写入对象
os.writeObject(lo1);
os.writeObject(lo2);
os.writeObject(lo3);
os.writeObject(lo4);
os.writeObject(lo5);
}catch(Exception ex){
ex.printStackTrace();
}
boolean ok = true; // 17.7
double ans = 0;
try{
ObjectInputStream input = new ObjectInputStream(new FileInputStream("f.dat")); // 接收对象
while(ok){
Loan a = (Loan)input.readObject(); // 向下转换
ans += a.getlo();
//System.out.println( "***"+ ans);
}
}catch (Exception E){
System.out.println("All data were read and ans is : " + ans);
ok = false;
}
}
}