Contenidos
Serializar
Serializar significa transformar un objeto en una secuencia de bytes para escribirlo en un stream.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.io.*; import java.util.Date; public class Serializar { public static void main(String[] args) { try { FileOutputStream fos = new FileOutputStream("fichero.txt"); ObjectOutputStream sos = new ObjectOutputStream(fos); sos.writeObject("Fecha actual"); sos.writeObject(new Date()); sos.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } } |
Deserializar
Deserializar significa transformar una secuencia de bytes leída de un stream en un objeto.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.io.*; import java.util.Date; public class Deserializar { public static void main(String[] args) { try { FileInputStream fis = new FileInputStream("fichero.txt"); ObjectInputStream sis = new ObjectInputStream(fis); System.out.println((String)sis.readObject()); System.out.println((Date)sis.readObject()); sis.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } catch(ClassNotFoundException ex) { ex.printStackTrace(); } } } |