序列化的读写磁盘细节很多。
上个最简单实例.
1.序列化的类要implements Serializable
2.不参与序列化的用transient
3. 接口用 extends比如:public interface Strategy extends Serializable
知道以上3点基本够用了。
public class SerializeTest {
private Assert Assertions;
@Test
public void testwrite() {
try {
T t = new T();
File f = new File("/Users/Desktop/java/ideaPrj/a.dat");
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(t);
oos.flush();
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testload() {
try {
File f = new File("/Users/Desktop/java/ideaPrj/a.dat");
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
T t = (T) (ois.readObject());
System.out.println(t.m + " " + t.n);
// Assertions.assertEquals(4,t.m);
//Assertions.assertEquals(8,t.n);
//Assertions.assertEquals(3,t.a.weight);
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class T implements Serializable {
int m = 4;
int n=8;
// transient int n = 8;//不参与序列化
// Apple a =new Apple();
}
class Apple implements Serializable
{
int weight =3;
}
/*
public interface Strategy extends Serializable
*/