Junior — Middle
What methods do you know for saving object data when restarting the application?
sobes.tech AI
Answer from AI
To save object data when restarting an application in Java, several methods can be used:
- Serialization — converting an object into a byte stream and saving it to a file or database.
- Saving to a database — for example, using JDBC or ORM (Hibernate).
- Using file storage — writing data to text or binary files.
- Preferences API — for saving simple settings and parameters.
Example of object serialization:
import java.io.*;
class User implements Serializable {
String name;
int age;
User(String name, int age) {
this.name = name;
this.age = age;
}
}
// Saving the object
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("user.dat"))) {
User user = new User("Ivan", 30);
oos.writeObject(user);
} catch (IOException e) {
e.printStackTrace();
}
// Loading the object
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("user.dat"))) {
User user = (User) ois.readObject();
System.out.println(user.name + ", " + user.age);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}