48 lines
1.4 KiB
Java
48 lines
1.4 KiB
Java
|
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);
|
||
|
|
||
|
// Dateiname für die Serialisierung
|
||
|
String dateiname = "serializedProduct.xml";
|
||
|
|
||
|
// Serialisierung
|
||
|
Main.serialize(product, dateiname);
|
||
|
|
||
|
// Deserialisierung und Ausgabe
|
||
|
Product decodedProduct = Main.deserialize(product, dateiname);
|
||
|
System.out.printf("Name: %s\nDes: %s\nPrice: %s", decodedProduct.getName(),decodedProduct.getDescription(),decodedProduct.getPrice());
|
||
|
}
|
||
|
|
||
|
// Methode zur Serialisierung eines Produkts
|
||
|
public static void serialize (Product product, String dateiname) {
|
||
|
try (XMLEncoder encoder = new XMLEncoder(new FileOutputStream(dateiname))){
|
||
|
encoder.writeObject(product);
|
||
|
} 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;
|
||
|
}
|
||
|
}
|
||
|
|