直接将Object写入或写出
transient关键字
serializable接口
externalizable接口
例子一、
public class Test { public static void main(String[] args) { try { T t = new T(); t.k = 18; FileOutputStream fos = new FileOutputStream("d:/bak/testobjectio.dat"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(t); oos.flush(); oos.close(); FileInputStream fis = new FileInputStream("d:/bak/testobjectio.dat"); ObjectInputStream ois = new ObjectInputStream(fis); T t2 = (T) ois.readObject(); System.out.println(t2.i + "//" + t2.j + "//" + t2.d + "//" + t2.k); } catch (Exception e) { e.printStackTrace(); } } } class T implements Serializable { int i = 10; int j = 9; double d = 2.3; int k = 15; }
结果:
10//9//2.3//18
例子二、
用transient修饰变量k
class T implements Serializable { int i = 10; int j = 9; double d = 2.3; transient int k = 15; }
结果:
10//9//2.3//0
transient修饰的变量k不会被写入进去,所以取出来的k为空,为默认值0
时间: 2024-10-29 09:30:18