`

数据多版本的读写

    博客分类:
  • Java
 
阅读更多

引子:在编写程序的时候,所有时间的变化、对基本的数据通常要更新,如一个学生类,一开始的时候,我们只想到了保存姓名,出生年月的属性,后来我们又想加入学生性别的属性了,后来又想加入学生的地址了。如何才能做到读写统一呢?

 

例子:

例子中给出了类D1_0-》D1_1-》D1_2,这三个类是继承关系,D1_0中只有d1,隔了一段时间想加入d2,写了类D1_1,又想加d3,写了类D1_2。数据保存的时候通常是个数组,这样我们假设写的时候写的数组始终是数组D1_0【】,读的时候也是。这样数据属性的变化,读写程序就不需要变了。

 

注意点:

1,旧版本的数据读入后,增加的数据又是新的版本,这样直接把旧的转化为新的数据,并成一个新数组写出了。

2,没有考虑,覆盖的问题,如果后来的数据想少些怎么办?现在认为不处理就行了。

3,。。。

 

public class Tsts {
	private static String file1_0 = "data1.0.txt";
	private static String file1_1 = "data1.1.txt";
	private static String file1_2 = "data1.2.txt";
	
	public static void main(String[] args) {
		D1_0[] d0A = new D1_0[]{new D1_0(),new D1_0(),new D1_0()}; // data version 1.0
		D1_1[] d1A = new D1_1[]{new D1_1(),new D1_1()}; // data version 1.1
		D1_2[] d2A = new D1_2[]{new D1_2(),new D1_2(),new D1_2(),new D1_2()}; // data version 1.2

		D1_0[] readData;
		// data version 1.0
		saveData(file1_0, d0A);
		readData = loadData(file1_0);
		for(D1_0 d : readData) {d.print();}

		// data version 1.1
		saveData(file1_1, d1A);
		readData = loadData(file1_1);
		for(D1_0 d : readData) {d.print();}
		
		// data version 1.2
		saveData(file1_2, d2A);
		readData = loadData(file1_2);
		for(D1_0 d : readData) {d.print();}

	}

	private static void saveData(String file, D1_0[] d0A) {
		ObjectOutputStream oos=null;
		try {
			FileOutputStream fos = new FileOutputStream(file);
			oos = new ObjectOutputStream(fos);
			oos.writeObject(d0A);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(oos != null) {
				try {
					oos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	private static D1_0[] loadData(String file) {
		D1_0[] d0A=null ;
		ObjectInputStream ois=null;
		try {
			FileInputStream fis = new FileInputStream(file);
			ois = new ObjectInputStream(fis);
			d0A = (D1_0[])ois.readObject();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return d0A;
	}
}
class D1_0 implements Serializable{
	private static final long serialVersionUID = -5747074459156767211L;
	private int d0;
	public void print() {System.out.println("D1_0 data version 1.0");}
}
class D1_1 extends D1_0 {
	private static final long serialVersionUID = -9091624871086037966L;
	private int d1;
	public void print() {System.out.println("D1_1 data version 1.1");}
}
class D1_2 extends D1_1 {
	private static final long serialVersionUID = -5704053473053777096L;
	private int d2;
	public void print() {System.out.println("D1_2 data version 1.2");}
}

 

结果 写道

D1_0 data version 1.0
D1_0 data version 1.0
D1_0 data version 1.0
D1_1 data version 1.1
D1_1 data version 1.1
D1_2 data version 1.2
D1_2 data version 1.2
D1_2 data version 1.2
D1_2 data version 1.2

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics