写一个Java的序列化与反序列化工具类
时间: 2024-05-01 20:17:31 浏览: 171
好的,关于Java的序列化与反序列化工具类,我可以提供一些建议和示例代码。在Java中,对象序列化可以用来将一个对象的状态保存到一个字节流中,而对象的反序列化则可以把这个字节流中的对象状态恢复回来。在实际应用中,序列化和反序列化常常用在数据存储、网络传输等场景中。
以下是一个简单的序列化与反序列化工具类示例:
```
import java.io.*;
public class SerializationUtil {
public static void serialize(Object obj, String fileName) throws IOException {
try (FileOutputStream fos = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(obj);
System.out.println("Serialization successful");
}
}
public static Object deserialize(String fileName) throws IOException, ClassNotFoundException {
try (FileInputStream fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis)) {
Object obj = ois.readObject();
System.out.println("Deserialization successful");
return obj;
}
}
}
```
对于一个需要被序列化的对象,它需要实现Serializable接口。例如:
```
import java.io.Serializable;
public class User implements Serializable {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "name=" + name + ", age=" + age;
}
}
```
使用方法如下:
```
User user = new User("John", 28);
SerializationUtil.serialize(user, "user.bin");
User newUser = (User) SerializationUtil.deserialize("user.bin");
System.out.println("Deserialized user: " + newUser);
```
输出:
```
Serialization successful
Deserialization successful
Deserialized user: name=John, age=28
```
希望这个工具类示例可以对你有所帮助!
阅读全文