Sérialisation redéfinie


Rappel

transcient empêche la sérialisation

public class LoggingInfo 
      implements  Serializable 
{ 
  private Date loggingDate = new Date(); 
  private String uid; 
  private transient String pwd; 
  LoggingInfo(String user, String password) { 
    uid = user; 
    pwd = password; 
  } 
  public String toString() { 
    String password=null; 
    if (pwd == null) 
      password = "";  
    else 
      password = pwd;  
    return "logging info: \n   " + "user: " + uid 
          + "\n   date : " + loggingDate.toString()
          + "\n   password: " + password; 
  } 
}

Redéfinir la sérialisation

Voici le source de Vect.java qui est une implémentation minimale de Vector mais optimale quant à sa sérialisation :
import java.io.*;
public class Vect 
       implements Serializable {
  private Object[] tabElement = new Object[10];
  private transient int taille = 0;
  
  public Object elementAt(int index) 
      throws ArrayIndexOutOfBoundsException {
    if (index >= taille)
      throw new ArrayIndexOutOfBoundsException(index);
    else 
      return tabElement[index];
  }
  public void add(Object element) {
    if (tabElement.length == taille)
      resize(tabElement.length*2);
    tabElement[taille++] = element;
  }
  private void resize(int taille) {
    Object[] newTabElement = new Object[taille];
    System.arraycopy(tabElement, 0, newTabElement, 0, taille);
    tabElement = newTabElement;
  }
  private void writeObject(ObjectOutputStream flotOut) 
         throws IOException {
    if (tabElement.length > taille)
      resize(taille);
    flotOut.defaultWriteObject();
  }
  private void readObject(ObjectInputStream flotIn) 
        throws IOException, ClassNotFoundException
  {
    flotIn.defaultReadObject();
    taille = tabElement.length;
  }
}

Source de TestVect.java

import java.io.*;
import java.util.*;
public class TestVect  {
  public static void main(String args[]) {
    if (args.length!=1) {
      System.out.println("argument nom_de_fichier !");
      System.exit(0);
    }
    try {
      System.out.println("combien de mots ?");
      int combien= Clavier.lireInt();
      String mot;
      Vector vector = new Vector(10);
      Vect vect = new Vect();
      for (int i=0; i<combien; i++) {
        System.out.println("donnez un mot\n");
        mot = Clavier.lireString();
        vector.add(mot);
        vect.add(mot);
      }  
      
      ObjectOutputStream flotEcriture = 
              new ObjectOutputStream(
                    new FileOutputStream(new File (args[0]+".Vector")));
      flotEcriture.writeObject(vector);
      flotEcriture.close();
      flotEcriture = 
              new ObjectOutputStream(
                    new FileOutputStream(new File (args[0]+".Vect")));
      flotEcriture.writeObject(vect);
      flotEcriture.close();
      
    } catch (IOException e) {
      System.out.println(" erreur :" + e.toString());
    }      
  }
}

exercice