SerializableTest序列化的作用
对象状态转换为可保持或传输的格式的过程称为序列化(两个对象反过来称反序列化),主要可以轻松地存储和传输数据。
测试过程:随便写个类,然后去实习序列化接口
public class SerializableTest implements Serializable {
private static final long serialVersionUID = 1L; //在运行时判断类的serialVersionUID来验证版本一致性
private String name;
private int num;
public SerializableTest(String name,int num){
this.name = name;
this.num = num;
}
public String toString(){
return ("name:"+name+"num:"+num);
}
}
再写一个类的调用上面所述已序列化的类
public class ObjectSerializationApp {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("test1.dat"));
outputStream.writeObject(new SerializableTest("nancy",3));//通过一个writeObject方法轻松将对象转化为可保持或传输的格式,放入test1.dat文件当中
outputStream.writeObject(new SerializableTest("jack",4));
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("test1.dat"));
for (int i = 0; i < 2; i++) {
System.out.println(objectInputStream.readObject());
}
try {
if (outputStream != null)
outputStream.close();
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
对比近乎等同效果
public class FileOutputStreamTest {
public static void main(String[] args) {
try {
String path = "test001.txt";
File file = new File(path);
FileOutputStream fileOutputStream = new FileOutputStream(file);
for (int i = 0; i <2; i++) {
fileOutputStream.write(new SerializableTest("测试1",1).toString().getBytes());
fileOutputStream.write(("\n").getBytes());
}
BufferedReader Input = new BufferedReader(new FileReader("test001.txt"));
for (int i = 0; i < 2; i++) {
System.out.println(Input.readLine());
}
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e){
e.printStackTrace();
}
}
}
//1:不用每个对象加toString().getBytes()
//2:获取字符串内容还需要换为BufferedReader类,并且灵活性质不高