The ObjectInputStream
and ObjectOutputStream
classes in Java are used to serialize and deserialize objects. Serialization is the process of converting an object into a byte stream, making it possible to save the object's state to a file or transmit it over a network. Deserialization is the reverse process of converting the byte stream back into a copy of the object.
Here's a simple example to demonstrate how to use these classes:
import java.io.*;
// Class to be serialized
class Person implements Serializable {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}
public class Example {
public static void main(String[] args) {
// Serialize the object
Person person = new Person("Alice", 30);
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"))) {
oos.writeObject(person);
} catch (IOException e) {
e.printStackTrace();
}
// Deserialize the object
Person deserializedPerson = null;
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"))) {
deserializedPerson = (Person) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("Deserialized Person: " + deserializedPerson);
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?