Serializables

Spread the love

Example of a serialization

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bestpractices;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
*
* @author VonTalavang
*/
public class Serialisables {

public static void main(String[] args) {
String nombreArchivo = “goddamnit.dat”;
try {
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(nombreArchivo));
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(new ClaseTest(“go da hell 1”, “best game ever”));
oos.writeObject(new ClaseTest(“go da hell 2”, “worst game ever”));

oos.close();
bos.close();

BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(nombreArchivo));
ObjectInputStream ois = new ObjectInputStream(bis);
ClaseTest entrada = (ClaseTest) ois.readObject();
while (true) {
System.out.println(entrada);
entrada = (ClaseTest) ois.readObject();
}
} catch (FileNotFoundException ex) {
//Logger.getLogger(Serialisables.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
Logger.getLogger(Serialisables.class.getName()).log(Level.SEVERE, null, ex);
}

}

private static class ClaseTest implements Serializable {

private String frase1;
private String frase2;

public ClaseTest() {
}

public String getFrase1() {
return frase1;
}

public void setFrase1(String frase1) {
this.frase1 = frase1;
}

public String getFrase2() {
return frase2;
}

public void setFrase2(String frase2) {
this.frase2 = frase2;
}

public ClaseTest(String frase1, String frase2) {
this.frase1 = frase1;
this.frase2 = frase2;
}
@Override
public String toString() {
return “ClaseTest{”
+ “frase1=” + frase1
+ “, frase2=” + frase2
+ ‘}’;
}
}
}

Comments

comments

Leave a Reply