Difference between revisions of "Entradas e Saídas em Java/Exemplo 04: Serialização de Objectos"

From Wiki**3

< Entradas e Saídas em Java
(Created page with "== Serialização de Objectos == Serialização de tipos primitivos e de objectos: a interface Serializable. Elementos não serializáveis: a palavra chave transient. === Exem...")
 
(Exemplo: Zorg e Zog)
 
(2 intermediate revisions by the same user not shown)
Line 5: Line 5:
 
=== Exemplo: Zorg e Zog ===
 
=== Exemplo: Zorg e Zog ===
  
<java5>
+
<source lang="java">
 
class Alienígena implements Serializable {
 
class Alienígena implements Serializable {
 
   String _nome;
 
   String _nome;
Line 12: Line 12:
 
   public void voing() { System.out.println(_nome + (_segredo != null ? _segredo : "")); }
 
   public void voing() { System.out.println(_nome + (_segredo != null ? _segredo : "")); }
 
}
 
}
</java5>
+
</source>
  
<java5>
+
<source lang="java">
public class Serialização {
+
  public class Serialização {
  public static void main(String[] args) throws IOException, ClassNotFoundException {
+
    public static void main(String[] args) {
  
    Alienígena a1 = new Alienígena("Zorg"), a2 = new Alienígena("Zog");
+
      Alienígena a1 = new Alienígena("Zorg"), a2 = new Alienígena("Zog");
    a1.voing(); //output: ZorgZorg4
+
      a1.voing(); // output: ZorgZorg4
    a2.voing(); //output: ZogZog3
+
      a2.voing(); // output: ZogZog3
  
    ObjectOutputStream out =
+
      try (ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("raw.dat")))) {
      new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("raw.dat")));
+
        out.writeObject(a1);
    out.writeObject(a1); out.writeObject(a2);
+
        out.writeObject(a2);
    out.close();
+
      } catch (IOException e) {
 +
        e.printStackTrace();
 +
      }
  
    ObjectInputStream in =
+
      try (ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream("raw.dat")))) {
      new ObjectInputStream(new BufferedInputStream(new FileInputStream("raw.dat")));
+
        Alienígena r1 = (Alienígena) in.readObject(); // pode lançar “StreamCorruptedException”
    Alienígena r1 = (Alienígena)in.readObject(); // pode lançar “StreamCorruptedException”
+
        Alienígena r2 = (Alienígena) in.readObject();
    Alienígena r2 = (Alienígena)in.readObject();
+
        r1.voing(); // output: Zorg
    r1.voing(); //output: Zorg
+
        r2.voing(); // output: Zog
    r2.voing(); //output: Zog
+
      } catch (FileNotFoundException e) {
 +
        e.printStackTrace();
 +
      } catch (IOException e) {
 +
        e.printStackTrace();
 +
      } catch (ClassNotFoundException e) {
 +
        e.printStackTrace();
 +
      }
  
 +
    }
 
   }
 
   }
}
+
</source>
</java5>
+
 
 +
Note-se que a função '''main''' declara o lançamento de excepções. Esta prática foi usada por simplicidade de exposição e não é ideal em geral: a função deveria tratar as excepções.
  
 
[[category:Ensino]]
 
[[category:Ensino]]

Latest revision as of 01:22, 6 November 2021

Serialização de Objectos

Serialização de tipos primitivos e de objectos: a interface Serializable. Elementos não serializáveis: a palavra chave transient.

Exemplo: Zorg e Zog

class Alienígena implements Serializable {
  String _nome;
  transient String _segredo = "7";
  public Alienígena(String n) { _nome = n; _segredo = _nome + _nome.length(); }
  public void voing() { System.out.println(_nome + (_segredo != null ? _segredo : "")); }
}
  public class Serialização {
    public static void main(String[] args) {

      Alienígena a1 = new Alienígena("Zorg"), a2 = new Alienígena("Zog");
      a1.voing(); // output: ZorgZorg4
      a2.voing(); // output: ZogZog3

      try (ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("raw.dat")))) {
        out.writeObject(a1);
        out.writeObject(a2);
      } catch (IOException e) {
        e.printStackTrace();
      }

      try (ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream("raw.dat")))) {
        Alienígena r1 = (Alienígena) in.readObject(); // pode lançar “StreamCorruptedException”
        Alienígena r2 = (Alienígena) in.readObject();
        r1.voing(); // output: Zorg
        r2.voing(); // output: Zog
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      }

    }
  }

Note-se que a função main declara o lançamento de excepções. Esta prática foi usada por simplicidade de exposição e não é ideal em geral: a função deveria tratar as excepções.