2024-04-20 14:18:44 +02:00
|
|
|
package Testat1.Tutor_Aufgaben.Serialisierung;
|
|
|
|
|
|
|
|
import java.beans.XMLDecoder;
|
|
|
|
import java.beans.XMLEncoder;
|
|
|
|
import java.io.FileInputStream;
|
|
|
|
import java.io.FileOutputStream;
|
|
|
|
import java.io.IOException;
|
|
|
|
|
|
|
|
public class Main {
|
|
|
|
public static void main(String[] args) {
|
|
|
|
// Erstelle ein Produkt
|
|
|
|
Product product = new Product("Handy", "ruft an", 299.99);
|
2024-05-07 14:03:28 +02:00
|
|
|
Product product2 = new Product("fdfl", "dfd", 34);
|
2024-04-20 14:18:44 +02:00
|
|
|
// Dateiname für die Serialisierung
|
|
|
|
String dateiname = "serializedProduct.xml";
|
|
|
|
|
|
|
|
// Serialisierung
|
|
|
|
Main.serialize(product, dateiname);
|
2024-05-07 14:03:28 +02:00
|
|
|
Main.serialize(product2, dateiname);
|
2024-04-20 14:18:44 +02:00
|
|
|
|
|
|
|
// Deserialisierung und Ausgabe
|
|
|
|
Product decodedProduct = Main.deserialize(product, dateiname);
|
2024-05-07 14:03:28 +02:00
|
|
|
Product decodedProduct1 = Main.deserialize(product2, dateiname);
|
2024-04-20 14:18:44 +02:00
|
|
|
System.out.printf("Name: %s\nDes: %s\nPrice: %s", decodedProduct.getName(),decodedProduct.getDescription(),decodedProduct.getPrice());
|
2024-05-07 14:03:28 +02:00
|
|
|
System.out.printf("Name: %s\nDes: %s\nPrice: %s", decodedProduct1.getName(),decodedProduct1.getDescription(),decodedProduct1.getPrice());
|
2024-04-20 14:18:44 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Methode zur Serialisierung eines Produkts
|
|
|
|
public static void serialize (Product product, String dateiname) {
|
|
|
|
try (XMLEncoder encoder = new XMLEncoder(new FileOutputStream(dateiname))){
|
|
|
|
encoder.writeObject(product);
|
2024-05-07 14:03:28 +02:00
|
|
|
|
2024-04-20 14:18:44 +02:00
|
|
|
} catch (IOException e) {
|
|
|
|
e.printStackTrace();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Methode zur Deserialisierung eines Produkts
|
|
|
|
public static Product deserialize (Product product, String dateiname) {
|
|
|
|
Product decodedProduct = null;
|
|
|
|
try (XMLDecoder decoder = new XMLDecoder(new FileInputStream(dateiname))){
|
|
|
|
decodedProduct = (Product) decoder.readObject();
|
|
|
|
|
|
|
|
} catch (Exception e) {
|
|
|
|
e.printStackTrace();
|
|
|
|
}
|
|
|
|
return decodedProduct;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|