Sérialisation xml en java

Fermé
limbaon9 Messages postés 42 Date d'inscription lundi 14 octobre 2019 Statut Membre Dernière intervention 12 mars 2022 - Modifié le 18 déc. 2021 à 14:00
KX Messages postés 16734 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 24 avril 2024 - 20 déc. 2021 à 13:35
Bonjour tout le monde, je suis étudiant en 3ème année de licence informatique et je bosse sur un projet en java dans lequel j'ai un petit soucis. Dans mon projet de jeu tamagotchi je veux integrer un moteur de "java objects Save&Reload engine" pour écrire dans un fichier xml quand je clique sur le boutton "sauvegarde" et restaurer les données quand je clique sur le boutton charger le(s) tamagotchi(s), mais pour ce qui est de ma question le lein entre le moteur et mon interface graphique ne sera pas abordé ici (peut-être quand j'aurai résolu ce problème :) ).
mon code est le suivant:
package minato;
import java.beans.ExceptionListener;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class XMLTamagotchiEncoderDecoder {

public static void main(String[] args) throws IOException 
    {
        tamagotchi tama = new tamagotchi("Ilias", true, 0, 0.0, 0, "rouge", 0, 0, 0, 0, "salon");
        tamagotchi.setNom("Assane");
        tama.setCouleur("Jaune");
        tama.setHumeur(false);
         
        //Before
        System.out.println(tama);
        serializeToXML ( tama );
        tamagotchi loadedTamas = deserializeFromXML();
        //After
        System.out.println(loadedTamas);
    }
     
    private static void serializeToXML (tamagotchi settings) throws IOException
    {
        FileOutputStream fos = new FileOutputStream("tamagotchis.xml");
        XMLEncoder encoder = new XMLEncoder(fos);
        encoder.setExceptionListener(new ExceptionListener(){
                public void exceptionThrown(Exception e) {
                    System.out.println("Exception! :"+e.toString());
                }
        });
        encoder.writeObject(settings);
        encoder.close();
        fos.close();
    }
     
    private static tamagotchi deserializeFromXML() throws IOException {
        FileInputStream fis = new FileInputStream("tamagotchis.xml");
        XMLDecoder decoder = new XMLDecoder(fis);
        tamagotchi decodedtamas = (tamagotchi) decoder.readObject();
        decoder.close();
        fis.close();
        return decodedtamas;
    }
}

et les erreurs que j'ai eues après compilations sont:
tamagotchi [humeur=false, taille=0.0, poids=0, couleur=Jaune, vitalite=0, hygiene=0, connaissance=0]
Exception! :java.lang.InstantiationException: minato.tamagotchi
Exception! :java.lang.Exception: XMLEncoder: discarding statement XMLEncoder.writeObject(tamagotchi);
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
at java.desktop/java.beans.XMLDecoder.readObject(XMLDecoder.java:251)
at minato.XMLTamagotchiEncoderDecoder.deserializeFromXML(XMLTamagotchiEncoderDecoder.java:43)
at minato.XMLTamagotchiEncoderDecoder.main(XMLTamagotchiEncoderDecoder.java:21)

je cherche depuis quelques jours à résoudre ce problème mais j'y arrive pas donc si quelqu'un peut m'aider à le résoudre je lui serai vraiment très reconnaissant.
Merci d'avance.
A voir également:

2 réponses

KX Messages postés 16734 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 24 avril 2024 3 015
18 déc. 2021 à 14:53
Bonjour,

Je t'invites à modifier l'ExceptionListener pour avoir la stack complète de l'erreur, pas juste son message. Les causes de l'exception peuvent contenir des informations importantes pour déboguer, puisque ce sont les plus proches de l'erreur.

Par exemple, ton erreur
java.lang.InstantiationException: minato.tamagotchi
pourrait être
Caused by: java.lang.NoSuchMethodException: minato.tamagotchi.<init>()
ce qui signifie qu'il te manque le constructeur
public tamagotchi(){}
dans la classe tamagotchi.

Mais sans le code de la classe tamagotchi (les données que tu (dé)sérialises), difficile de t'aider davantage, mais attention il y a des bizarreries, comme la méthode setNom qui est static...

Voir aussi la documentation :
0
limbaon9 Messages postés 42 Date d'inscription lundi 14 octobre 2019 Statut Membre Dernière intervention 12 mars 2022
18 déc. 2021 à 16:38
Merci d'abord pour votre réponse et j'ai quand même réussi à exécuter le programme sans erreur mais sauf qu'au lieu des 11 attributs qui doivent être sérialisés seuls deux apparaissent dans mon fichier "tamagotchis.xml" à savoir "humeur" et "couleur":

<?xml version="1.0" encoding="UTF-8"?>
<java version="14.0.1" class="java.beans.XMLDecoder">
<object class="minato.tamagotchi">
<void property="couleur">
<string>rouge</string>
</void>
<void property="humeur">
<boolean>true</boolean>
</void>
</object>
</java>
0
KX Messages postés 16734 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 24 avril 2024 3 015 > limbaon9 Messages postés 42 Date d'inscription lundi 14 octobre 2019 Statut Membre Dernière intervention 12 mars 2022
18 déc. 2021 à 17:22
Il faudrait voir le code de la classe Tamagotchi pour t'aider, c'est elle qui définit les données à stocker ou non dans le fichier...
0
limbaon9 Messages postés 42 Date d'inscription lundi 14 octobre 2019 Statut Membre Dernière intervention 12 mars 2022
Modifié le 20 déc. 2021 à 13:25
package minato;

import java.util.Random;
import java.util.Scanner;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import java.util.*;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.*;

public class tamagotchi extends JPanel {
    public static JFrame f = new JFrame();
    // f.setSize(300,300);
    static JLabel l = new JLabel();

    // static //String type; // animal ou robot ou autre ...
    private static String nom;
    private Boolean humeur;
    private static int age;
    private double taille;
    private int poids;
    private String couleur;
    private int vitalite;
    private int hygiene;
    private static int fatigue;
    private int connaissance;
    // int diligence;
    private static String position;
    // String p ="Salon";

    // Constructeur de tamagotchi
    public tamagotchi(String nom, Boolean humeur, int age, double taille, int poids, String couleur, int vitalite, int fatigue, int hygiene, int connaissance, String position) {

        this.nom = nom;
        this.humeur = humeur;
        this.age = age;
        // age=30;
        this.taille = taille;
        this.poids = poids;
        this.couleur = couleur;
        this.vitalite = vitalite;
        this.hygiene = hygiene;
        this.fatigue = fatigue;
        this.connaissance = connaissance;

        // this.diligence=diligence;
        this.position = position;
    }

    public tamagotchi(){
    };

    public Boolean getHumeur(){
        return humeur;
    }

    public void setHumeur(Boolean humeur) {
        this.humeur = humeur;
    }

    public double getTaille(){
        return taille;
    }

    public void setTaille(double taille) {
        this.taille = taille;
    }

    public int getPoids(){
        return poids;
    }

    public void setPoids(int poids) {
        this.poids = poids;
    }

    public String getCouleur(){
        return couleur;
    }

    public void setCouleur(String couleur) {
        this.couleur = couleur;
    }

    public int getVitalite(){
        return vitalite;
    }

    public void setVitalite(int vitalite) {
        this.vitalite = vitalite;
    }

    public int getHygiene(){
        return hygiene;
    }

    public void setHygiene(int hygiene) {
        this.hygiene = hygiene;
    }

    public static int getFatigue(){
        return fatigue;
    }

    public static void setFatigue(int fatigue) {
        tamagotchi.fatigue = fatigue;
    }

    public int getConnaissance(){
        return connaissance;
    }

    public void setConnaissance(int connaissance) {
        this.connaissance = connaissance;
    }

    public static int getAge(){
        return age;
    }

    public static String getNom(){
        return nom;
    }

    public static void setNom(String n) {
        nom = n;
    }

    public static String getPosition(){
        return position;
    }

    public static void setPosition(String position) {
        tamagotchi.position = position;
    }

    @Override
    public String toString(){
        return "tamagotchi [humeur=" + humeur + ", taille=" + taille + ", poids=" + poids + ", couleur=" + couleur + ", vitalite=" + vitalite + ", hygiene=" + hygiene + ", connaissance=" + connaissance + "]";
    }

//m?thodes 
    static void se_deplacer(){

        if (position == null) {
            setPosition("Salon");
            Salon salon = new Salon(); // Cree un objet Jardin
            JLabel l = salon.monSalonJlabel(); // Appel la methode monSalonJLabel et stocke le resultat dans une variable l.

            f.setContentPane(l);
            f.repaint();
            f.revalidate();
            f.setSize(600, 600);
            f.setVisible(true);
        }
        if (position == "Salon") {

            Salon salon = new Salon(); // Cree un objet Jardin
            JLabel s = salon.monSalonJlabel(); // Appel la methode monSalonJlabel et stocke le resultat dans une variable l.

            f.setContentPane(s);
            f.repaint();
            f.revalidate();
            f.setSize(600, 600);
            f.setVisible(true);

            System.out.println("Ou veux tu te deplacer ?\n");
            System.out.println("Jardin\n");
            System.out.println("Chambre\n");
            System.out.println("Cuisine.");

            Scanner saisiePosition = new Scanner(System.in);
            String choix = saisiePosition.nextLine();

            if (choix.equals("Jardin") || choix.equals("jardin")) {
                setPosition("Jardin");
                Jardin Jardin = new Jardin(); // Cree un objet Jardin
                JLabel l = Jardin.monJardinJlabel(); // Appel la methode monJardinJlabel et stocke le resultat dans une variable l.

                f.setContentPane(l);
                f.repaint();
                f.revalidate();
                // f.setSize(300,300);
                f.setVisible(true);

                System.out.println("Vous etes maintenant dans le jardin.");

            }

            if (choix.equals("Chambre") || choix.equals("chambre")) {
                setPosition("Chambre");
                Chambre chambre = new Chambre();// Cree un objet Chambre
                JLabel l = Chambre.maChambreJLabel(f);// Appel la methode maChambreJLabel de la classe Chambre + met le resultat dans
                                                      // une variable l.
                // JLabel l2 = Chambre.avatarJlabel();
                // f.setSize(300,300);
                f.setContentPane(l);

                f.repaint();
                f.revalidate();
                f.setVisible(true);
                System.out.println("Vous etes maintenant dans la chambre.");

            }

            if (choix.equals("Cuisine") || choix.equals("cuisine")) {
                setPosition("Cuisine");
                Cuisine cuisine = new Cuisine();
                JLabel l = cuisine.maCuisineJlabel();
                // f.setSize(300,300);
                f.setContentPane(l);
                f.repaint();
                f.revalidate();
                f.setVisible(true);
                System.out.println("Vous etes maintenant dans la cuisine.");
                // System.exit(0);

            }

            if (choix.equals("Jardin") == false && choix.equals("jardin") == false && choix.equals("Chambre") == false && choix.equals("chambre") == false && choix.equals("Cuisine") == false && choix.equals("cuisine") == false) {
                System.out.println("Vous n'avez pas fait le bon choix.");
            }
        }

        if (position == "Jardin") {
            System.out.println("Ou veux tu te deplacer ?\n");
            System.out.println("Salon\n");
            System.out.println("Chambre.");

            Scanner saisiePosition = new Scanner(System.in);
            String choix = saisiePosition.nextLine();
            if (choix.equals("Salon") || choix.equals("salon")) {
                setPosition("Salon");
                Salon salon = new Salon();
                JLabel l = Salon.monSalonJlabel();

                // f.setSize(300,300);
                f.setContentPane(l);
                f.repaint();
                f.revalidate();
                f.setVisible(true);
                System.out.println("Vous etes maintenant dans le salon.");
                // System.exit(0);
            }

            if (choix.equals("Chambre") || choix.equals("chambre")) {
                setPosition("Chambre");
                Chambre chambre = new Chambre();
                JLabel l = chambre.maChambreJLabel(f);

                // f.setSize(300,300);
                f.setContentPane(l);
                f.repaint();
                f.revalidate();
                f.setVisible(true);
                System.out.println("Vous etes maintenant dans la chambre.");
                // System.exit(0);

            }

            if (choix.equals("Chambre") == false && choix.equals("chambre") == false && choix.equals("Salon") == false && choix.equals("salon") == false) {
                System.out.println("Vous n'avez pas fait le bon choix.");
                System.exit(0);

            }

        }

        if (position == "Chambre") {
            System.out.println("Ou veux tu te deplacer ?\n");
            System.out.println("Salon\n");
            System.out.println("Jardin\n");
            System.out.println("Salle de bain.");

            Scanner saisiePosition = new Scanner(System.in);
            String choix = saisiePosition.nextLine();
            if (choix.equals("Jardin") || choix.equals("jardin")) {
                setPosition("Jardin");
                Jardin jardin = new Jardin();
                JLabel l = Jardin.monJardinJlabel();

                // f.setSize(300,300);
                f.setContentPane(l);
                f.repaint();
                f.revalidate();
                f.setVisible(true);
                System.out.println("Vous etes maintenant dans le jardin.");
                // System.exit(0);

            }

            if (choix.equals("Salon") || choix.equals("salon")) {
                setPosition("Salon");
                Salon salon = new Salon();
                JLabel l = Salon.monSalonJlabel();

                // f.setSize(300,300);
                f.setContentPane(l);
                f.repaint();
                f.revalidate();
                f.setVisible(true);
                System.out.println("Vous etes maintenant dans le salon.");
                // System.exit(0);

            }
            if (choix.equals("Salle de bain") || choix.equals("salle de bain")) {
                setPosition("Salle de bain");
                Salle_de_bain sdb = new Salle_de_bain();
                JLabel l = sdb.maSalledebainJlabel();

                // f.setSize(300,300);
                f.setContentPane(l);
                f.repaint();
                f.revalidate();
                f.setVisible(true);
                System.out.println("Vous etes maintenant dans la salle de bain.");
                // System.exit(0);

            }

            if (choix.equals("Salon") == false && choix.equals("salon") == false && choix.equals("Jardin") == false && choix.equals("jardin") == false && choix.equals("Salle de bain") == false && choix.equals("salle de bain") == false) {
                System.out.println("Vous n'avez pas fait le bon choix.");
                System.exit(0);

            }
        }

        if (position == "Cuisine") {
            System.out.println("Ou veux tu te deplacer ?\n");
            System.out.println("salon\n");
            System.out.println("salle de bain\n");

            Scanner saisiePosition = new Scanner(System.in);
            String choix = saisiePosition.nextLine();
            if (choix.equals("salon") || choix.equals("Salon")) {
                setPosition("Salon");
                Salon Salon = new Salon();
                JLabel l = Salon.monSalonJlabel();

                // f.setSize(300,300);
                f.setContentPane(l);
                f.repaint();
                f.revalidate();
                f.setVisible(true);
                System.out.println("Vous etes maintenant dans le salon.");
                // System.exit(0);

            }

            if (choix.equals("Salle de bain") || choix.equals("salle de bain")) {
                setPosition("Salle de bain");
                Jardin Jardin = new Jardin();
                JLabel l = Jardin.monJardinJlabel();

                f.setContentPane(l);
                f.repaint();
                f.revalidate();
                System.out.println("Vous etes maintenant dans la salle de bain.");
                // System.exit(0);

            }

            if (choix.equals("Salle de bain") == false && choix.equals("salle de bain") == false && choix.equals("Salon") == false && choix.equals("salon") == false) {
                System.out.println("Vous n'avez pas fait le bon choix.");
                System.exit(0);

            }

        }

        if (position == "Salle de bain") {
            System.out.println("Ou veux tu te deplacer ?\n");
            System.out.println("Chambre\n");
            System.out.println("Cuisine.");

            Scanner saisiePosition = new Scanner(System.in);
            String choix = saisiePosition.nextLine();

            if (choix.equals("Chambre") || choix.equals("chambre")) {
                setPosition("Chambre");
                Chambre Chambre = new Chambre();
                JLabel l = Chambre.maChambreJLabel(f);
                ;
                f.setContentPane(l);
                f.repaint();
                f.revalidate();
                System.out.println("Vous etes maintenant dans la chambre.");
                // System.exit(0);

            }
            if (choix.equals("Cuisine") || choix.equals("cuisine")) {
                setPosition("Cuisine");
                Cuisine Cuisine = new Cuisine();
                JLabel l = Cuisine.maCuisineJlabel();

                f.setContentPane(l);
                f.repaint();
                f.revalidate();
                System.out.println("Vous etes maintenant dans la cuisine.");
                // System.exit(0);

            }

            if (choix.equals("Cuisine") == false && choix.equals("cuisine") == false && choix.equals("Chambre") == false && choix.equals("chambre") == false) {
                System.out.println("Vous n'avez pas fait le bon choix.");
                System.exit(0);

            }
        }

    }

    static void etudier(){
        System.out.println("Math?matique, tapez 1.");
        System.out.println("Culture G?n?rale, tapez 2.");
        Scanner saisieMatiere = new Scanner(System.in);
        String choix = saisieMatiere.nextLine();

        if (choix.equals("1")) {
            System.out.println("Choisissez l'op?ration : ");
            System.out.println("l'addition, tapez +");
            System.out.println("la multiplication, tapez *");
            System.out.println("la soustraction, tapez -");
            System.out.println("La division, tapez /");
            Scanner sasieOperation = new Scanner(System.in);
            String choix2 = sasieOperation.nextLine();

            if (choix2.equals("*")) {
                int min = 1;
                int max = 9;
                Random random = new Random();
                int a = random.nextInt(9 + 1) + 1;
                int b = random.nextInt(9 + 1) + 1;
                int c = random
0
KX Messages postés 16734 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 24 avril 2024 3 015
20 déc. 2021 à 13:35
Bonjour,

Il faut revoir le type de tes attributs :
    private static String nom;
    private Boolean humeur;
    private static int age;
    private double taille;
    private int poids;
    private String couleur;
    private int vitalite;
    private int hygiene;
    private static int fatigue;
    private int connaissance;
    // int diligence;
    private static String position;
    // String p ="Salon";

Pour que cela fonctionne, tu dois d'une part retirer les static qui n'ont rien à faire là, d'autre part modifier les types primitifs en leur objet associé (int → Integer, double → Double) en modifiant également les getter/setter :
    private String nom;
    private Boolean humeur;
    private Integer age;
    private Double taille;
    private Integer poids;
    private String couleur;
    private Integer vitalite;
    private Integer hygiene;
    private Integer fatigue;
    private Integer connaissance;
    //private Integer diligence;
    private String position;
    //private String p ="Salon";

À ce moment là, tu devrais avoir un XML complet.
1