java中序列化是什么,能用代码写两个例子吗
时间: 2023-12-10 22:39:19 浏览: 37
Java中的序列化是一种将对象转换为字节序列的过程,可以将这些字节序列写入文件或通过网络传输,以便在稍后时间重新构造出与原始对象一样的对象。序列化被广泛用于RMI(远程方法调用)、缓存和持久化等场景。
下面是两个Java序列化的例子:
1. 将对象序列化到文件
```java
import java.io.*;
public class SerializeDemo {
public static void main(String[] args) {
Employee e = new Employee();
e.name = "John Doe";
e.address = "123 Main St";
e.SSN = 123456789;
e.number = 101;
try {
FileOutputStream fileOut = new FileOutputStream("employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in employee.ser");
} catch(IOException i) {
i.printStackTrace();
}
}
}
class Employee implements java.io.Serializable {
public String name;
public String address;
public transient int SSN; // 对于敏感信息,使用transient关键字标记不进行序列化
public int number;
}
```
2. 将对象序列化到字节数组
```java
import java.io.*;
public class SerializeDemo {
public static void main(String[] args) {
Employee e = new Employee();
e.name = "John Doe";
e.address = "123 Main St";
e.SSN = 123456789;
e.number = 101;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(baos);
out.writeObject(e);
out.close();
byte[] bytes = baos.toByteArray();
baos.close();
System.out.println("Serialized data size: " + bytes.length);
} catch(IOException i) {
i.printStackTrace();
}
}
}
class Employee implements java.io.Serializable {
public String name;
public String address;
public transient int SSN; // 对于敏感信息,使用transient关键字标记不进行序列化
public int number;
}
```