Advertisement
Radoslav_03

2ri i posleden file

Nov 6th, 2023
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.00 KB | None | 0 0
  1. import java.io.*;
  2. import java.time.LocalDate;
  3. import java.util.Scanner;
  4.  
  5. public class Serialization {
  6.     public static void main(String[] args) {
  7.  
  8.         Scanner scanner = new Scanner(System.in);
  9.         System.out.print("Enter the amount of people: ");
  10.         int numberOfPeople = scanner.nextInt();
  11.         scanner.nextLine();
  12.  
  13.         Person[] people = new Person[numberOfPeople];
  14.  
  15.         for (int i = 0; i < numberOfPeople; i++) {
  16.             System.out.printf("Enter details for Person %d%n", (i + 1));
  17.             System.out.print("Name: ");
  18.             String name = scanner.nextLine();
  19.             System.out.print("Birth Year: ");
  20.             int birthYear = Integer.parseInt(scanner.nextLine());
  21.             System.out.print("Birth Month: ");
  22.             int birthMonth = Integer.parseInt(scanner.nextLine());
  23.             System.out.print("Birth Day: ");
  24.             int birthDay = Integer.parseInt(scanner.nextLine());
  25.  
  26.             LocalDate birthDate = LocalDate.of(birthYear, birthMonth, birthDay);
  27.             people[i] = new Person(name, birthDate);
  28.         }
  29.  
  30.         final String filePath = "people.bin";
  31.  
  32.         try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filePath))) {
  33.             out.writeObject(people);
  34.             System.out.println("Objects have been serialized and written to a file.");
  35.         } catch (IOException e) {
  36.             e.printStackTrace();
  37.         }
  38.  
  39.         try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(filePath))) {
  40.             Person[] peopleFromFile = (Person[]) in.readObject();
  41.  
  42.             for (Person person : peopleFromFile) {
  43.                 System.out.println("Name: " + person.getName());
  44.                 System.out.println("Birth Date: " + person.getBirth());
  45.                 System.out.println("Age: " + person.getAge());
  46.                 System.out.println();
  47.             }
  48.         } catch (IOException | ClassNotFoundException e) {
  49.             e.printStackTrace();
  50.         }
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement