Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.time.LocalDate;
- import java.util.Scanner;
- public class Serialization {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- System.out.print("Enter the amount of people: ");
- int numberOfPeople = scanner.nextInt();
- scanner.nextLine();
- Person[] people = new Person[numberOfPeople];
- for (int i = 0; i < numberOfPeople; i++) {
- System.out.printf("Enter details for Person %d%n", (i + 1));
- System.out.print("Name: ");
- String name = scanner.nextLine();
- System.out.print("Birth Year: ");
- int birthYear = Integer.parseInt(scanner.nextLine());
- System.out.print("Birth Month: ");
- int birthMonth = Integer.parseInt(scanner.nextLine());
- System.out.print("Birth Day: ");
- int birthDay = Integer.parseInt(scanner.nextLine());
- LocalDate birthDate = LocalDate.of(birthYear, birthMonth, birthDay);
- people[i] = new Person(name, birthDate);
- }
- final String filePath = "people.bin";
- try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filePath))) {
- out.writeObject(people);
- System.out.println("Objects have been serialized and written to a file.");
- } catch (IOException e) {
- e.printStackTrace();
- }
- try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(filePath))) {
- Person[] peopleFromFile = (Person[]) in.readObject();
- for (Person person : peopleFromFile) {
- System.out.println("Name: " + person.getName());
- System.out.println("Birth Date: " + person.getBirth());
- System.out.println("Age: " + person.getAge());
- System.out.println();
- }
- } catch (IOException | ClassNotFoundException e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement