在Java中,实现Serializable接口可以将对象序列化,我们通过几个小例子来分析序列化文件。
案例1
源代码
package com.kongpf.clazz;
import java.io.*;
public class Hello implements Serializable {
private static final long serialVersionUID = 0x12345678L;
private String name;
public Hello(String name) {
this.name = name;
}
public static void main(String[] args) throws CloneNotSupportedException {
String filePath = "hello.txt";
Hello hello = new Hello("jack");
try {
FileOutputStream fileOutputStream =
new FileOutputStream(filePath);
ObjectOutputStream outputStream =
new ObjectOutputStream(fileOutputStream);
outputStream.writeObject(hello);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
文件格式解析
用16进制编辑器HexFiend打开生成的hello.txt文件,内容如下:
![hex.png]()
文件可以分为3部分:文件头
、类描述
、字段描述
内容 |
说明 |
73 |
对象标识 |
72 |
类描述开始标识 |
0016 |
类名长度,22 |
636F6D2E 6B6F6E67 70662E63 6C617A7A 2E48656C 6C6F |
类名,com.kongpf.clazz.Hello |
0000 00001234 5678 |
serialVersionUID |
02 |
flag标识 |
00 01 |
字段的总数,1 |
4C |
字段类型,L |
0004 |
字段的长度,4 |
6E616D65 |
字段名称,name |
74 |
字段类型为String |
0012 |
字段类型的长度,18 |
4C6A6176 612F6C61 6E672F53 7472696E 673B |
字段类型名称,Ljava/lang/String; |
78 |
类描述结束标识 |
70 |
父类描述,70对应为NULL |
内容 |
说明 |
74 |
字段类型为String |
0004 |
字段长度,4 |
6A61 636B |
字段名称,jack |
案例2
源代码
package com.kongpf.serial;
import java.io.*;
enum Color {
RED,
GREEN,
BLUE
}
public class EnumExample {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("enum.txt");
ObjectOutputStream outputStream = new ObjectOutputStream(fos);
outputStream.writeObject(Color.BLUE);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
文件格式解析
用16进制编辑器HexFiend打开生成的hello.txt文件,内容如下:
![hex.png]()
文件可以分为3部分:文件头
、类描述
、字段描述
内容 |
说明 |
7E |
枚举对象标识 |
72 |
类描述开始标识 |
0017 |
类名长度,23 |
636F6D2E 6B6F6E67 70662E73 65726961 6C2E436F 6C6F72 |
类名,com.kongpf.serial.Color |
00000000 00000000 |
serialVersionUID |
12 |
flag标识 |
00 00 |
字段的总数,0 |
78 |
类描述结束标识 |
72 |
类描述开始标识 |
000E |
类名长度,14 |
6A617661 2E6C616E 672E456E 756D |
类名,java.lang.Enum |
00000000 00000000 |
serialVersionUID |
12 |
flag标识 |
00 00 |
字段的总数,0 |
78 |
类描述结束标识 |
70 |
父类描述,70对应为NULL |
内容 |
说明 |
74 |
字段类型为String |
0004 |
字段长度,4 |
424C5545 |
字段名称,BLUE |