编写程序,创建一个 Custom 类,定义一个 Custom 对象和一个 String 对象。实现这两个对象的序列化和反序列化。
时间: 2023-12-03 09:45:38 浏览: 28
下是一个示例代码,实现了 Custom 类和 String 类的序列化和反序列化:
```java
import java.io.*;
public class Custom implements Serializable {
private int id;
private String name;
public Custom(int id, String name) {
this.id = id;
this.name = name;
}
public static void main(String[] args) {
Custom custom = new Custom(1, "John");
String str = "Hello, world!";
// 序列化 Custom 对象
try {
FileOutputStream fileOut = new FileOutputStream("custom.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(custom);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in custom.ser");
} catch (IOException i) {
i.printStackTrace();
}
// 反序列化 Custom 对象
try {
FileInputStream fileIn = new FileInputStream("custom.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
Custom customIn = (Custom) in.readObject();
in.close();
fileIn.close();
System.out.println("Deserialized Custom object:");
System.out.println("ID: " + customIn.id);
System.out.println("Name: " + customIn.name);
} catch (IOException i) {
i.printStackTrace();
} catch (ClassNotFoundException c) {
System.out.println("Custom class not found");
c.printStackTrace();
}
// 序列化 String 对象
try {
FileOutputStream fileOut = new FileOutputStream("string.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(str);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in string.ser");
} catch (IOException i) {
i.printStackTrace();
}
// 反序列化 String 对象
try {
FileInputStream fileIn = new FileInputStream("string.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
String strIn = (String) in.readObject();
in.close();
fileIn.close();
System.out.println("Deserialized String object:");
System.out.println(strIn);
} catch (IOException i) {
i.printStackTrace();
} catch (ClassNotFoundException c) {
System.out.println("String class not found");
c.printStackTrace();
}
}
}
```
上述代码中,Custom 类实现了 Serializable 接口,表示这个类可以被序列化。在 main 方法中,首先创建了一个 Custom 对象和一个 String 对象,然后分别对它们进行序列化和反序列化。
序列化 Custom 对象的过程如下:
1. 创建一个 FileOutputStream 对象,用于将序列化数据写入文件。
2. 创建一个 ObjectOutputStream 对象,用于将 Custom 对象序列化到 FileOutputStream 中。
3. 调用 out.writeObject(custom) 方法,将 Custom 对象写入 ObjectOutputStream 中。
4. 调用 out.close() 方法关闭 ObjectOutputStream 和 FileOutputStream。
反序列化 Custom 对象的过程如下:
1. 创建一个 FileInputStream 对象,用于读取序列化数据文件。
2. 创建一个 ObjectInputStream 对象,用于从 FileInputStream 中反序列化 Custom 对象。
3. 调用 in.readObject() 方法,从 ObjectInputStream 中读取 Custom 对象。
4. 强制类型转换成 Custom 类型。
5. 调用 in.close() 方法关闭 ObjectInputStream 和 FileInputStream。
序列化和反序列化 String 对象的过程与 Custom 对象类似,只需将 Custom 类换成 String 类即可。