curso lenguaje java (archivos y seriacion 2010)
Post on 18-Jan-2016
62 Views
Preview:
TRANSCRIPT
gch@pumas.iingen.unam.mx
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernández
PDelValleM@iingen.unam.mx
11
ArchivosArchivosSecuencialesSecuenciales
gch@pumas.iingen.unam.mx
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernández
PDelValleM@iingen.unam.mx
22
Archivos con tipos primitivosArchivos con tipos primitivosLas siguientes clases permiten leer y escribir respectivamente datos de cualquier tipo de dato primitivo
Se crea un flujo asociado con un origen o destino de datosSe crea un flujo asociado con un origen o destino de datos Se asocia un filtro con el flujo anteriorSe asocia un filtro con el flujo anterior Finalmente, el programa leerá o escribirá a través de este filtroFinalmente, el programa leerá o escribirá a través de este filtro
Programa dis fis Archivo
Programa dos fos Archivo
DataInputStreamDataInputStream
DataOutputStreamDataOutputStream
gch@pumas.iingen.unam.mx
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernández
PDelValleM@iingen.unam.mx
33
Métodos de la clase DataOutputStreamMétodos de la clase DataOutputStream
gch@pumas.iingen.unam.mx
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernández
PDelValleM@iingen.unam.mx
44
Ejemplo escrituraEjemplo escritura//Crea los flujos de escrituraFileOutputStream fos = new FileOutputStream (“tareas.txt”);DataOutputStream dos = new DataOutputStream (fos);
//escribe datos al archivo
dos.writeUTF(“Juan López”);dos.writeInt(3245);dos.writeFloat(8500.00);dos.writeLong(56221214);
//cierra los flujos
dos.close();fos.close();
gch@pumas.iingen.unam.mx
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernández
PDelValleM@iingen.unam.mx
55
Métodos de la clase DataInputStreamMétodos de la clase DataInputStream
gch@pumas.iingen.unam.mx
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernández
PDelValleM@iingen.unam.mx
66
Ejemplo lecturaEjemplo lectura//Crea los flujos de lecturaFileInputStream fis = new FileInputStream (“tareas.txt”);DataInputStream dis = new DataInputStream (fis);
//Lee datos del archivo
nombre = dis.readUTF();clave =dis. readInt();sueldo = dis. readFloat();telefono = dis.readLong();
//cierra los flujos
dis.close();fis.close();
gch@pumas.iingen.unam.mx
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernández
PDelValleM@iingen.unam.mx
77
Ejemplo:Ejemplo:
Agenda telefónicaAgenda telefónica
gch@pumas.iingen.unam.mx
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernández
PDelValleM@iingen.unam.mx
88
import java.io.*;
public class MostrarListaTfnos{ public static void mostrarFichero(String nombreFichero) throws IOException { DataInputStream dis = null;// entrada de datos desde el fichero File fichero = null; // objeto que identifica el fichero // Declarar los datos a escribir en el fichero String nombre, dirección; String telefono;
Ejemplo Ejemplo MostrarListaTfnos
gch@pumas.iingen.unam.mx
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernández
PDelValleM@iingen.unam.mx
99
try { // Crear un objeto File que identifique al fichero fichero = new File (nombreFichero);
// Verificar si el fichero existe if (fichero.exists()) { // Si existe, abrir un flujo desde el mismo dis = new DataInputStream(new BufferedInputStream( new FileInputStream(fichero)));
gch@pumas.iingen.unam.mx
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernández
PDelValleM@iingen.unam.mx
1010
do { // Leer un nombre, una dirección y un teléfono desde el // fichero. Cuando se alcance el final del fichero Java // lanzará una excepción del tipo EOFException. nombre = dis.readUTF(); dirección = dis.readUTF(); telefono = dis.readUTF(); // Mostrar los datos nombre, dirección y teléfono System.out.println(nombre); System.out.println(dirección); System.out.println(telefono); System.out.println(); } while (true);
gch@pumas.iingen.unam.mx
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernández
PDelValleM@iingen.unam.mx
1111
else System.out.println("El fichero no existe"); } catch(EOFException e) { System.out.println("Fin del listado"); } finally { // Cerrar el flujo if (dis != null)
dis.close(); } }
gch@pumas.iingen.unam.mx
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernández
PDelValleM@iingen.unam.mx
1212
public static void main(String[] args) { String nombre_archivo = Teclado.cadena( "Nombre del archivo de lectura: "); try { mostrarFichero(nombre_archivo); } catch(IOException e) { System.out.println("Error: " + e.getMessage()); } }}
gch@pumas.iingen.unam.mx
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernández
PDelValleM@iingen.unam.mx
1313
import java.io.*;
public class CrearListaTfnos{ public static void crearFichero(File fichero) throws IOException { DataOutputStream dos = null;// salida de datos hacia el fichero
int resp; // Declarar los datos a escribir en el fichero
String nombre, dirección; String telefono;
Ejemplo Ejemplo CrearListaTfnos
gch@pumas.iingen.unam.mx
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernández
PDelValleM@iingen.unam.mx
1414
try { // Crear un flujo hacia el fichero que permita escribir // datos de tipos primitivos y que utilice un buffer. dos = new DataOutputStream(new BufferedOutputStream( new FileOutputStream(fichero))); do { nombre = Teclado.cadena("Nombre: "); dirección = Teclado.cadena("Direccion:"); telefono = Teclado.cadena("Telefono: ");
// Almacenar un nombre, una dirección y un teléfono en el fichero dos.writeUTF(nombre); dos.writeUTF(dirección); dos.writeUTF(telefono);
resp = Teclado.entero ("¿desea escribir otro registro 1)si 2) no? "); } while (resp == 1); }
gch@pumas.iingen.unam.mx
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernández
PDelValleM@iingen.unam.mx
1515
finally { // Cerrar el flujo if (dos != null) dos.close(); } }
public static void main(String[] args) { String nombreFichero = null; // nombre del fichero File fichero = null; // objeto que identifica el fichero
int opc;
gch@pumas.iingen.unam.mx
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernández
PDelValleM@iingen.unam.mx
1616
try { // Crear un objeto File que identifique al fichero nombreFichero = Teclado.cadena("Nombre del archivo: "); fichero = new File(nombreFichero); // Verificar si el fichero existe if (fichero.exists()) { opc = Teclado.entero("El archivo existe desea reescribirlo (1) si 2) no)? "); if (opc != 1)
return; } crearFichero(fichero); } catch(IOException e) { System.out.println("Error: " + e.getMessage()); } }}
gch@pumas.iingen.unam.mx
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernández
PDelValleM@iingen.unam.mx
Seriación Seriación
dede
ObjetosObjetos
1717
gch@pumas.iingen.unam.mx
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernández
PDelValleM@iingen.unam.mx
Seriación
La operación de enviar una serie de objetos a un archivo.
Deseriación
La operación de leer o recuperar objetos del archivo y reconstruirlos en la memoria
Para realizar estas operaciones automáticamente, el paquete java.io proporciona las clases
ObjectOutputStreamObjetcInputStream
gch@pumas.iingen.unam.mx
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernández
PDelValleM@iingen.unam.mx
1919
ObjectOutputStream ObjetcInputStream
Ambas clases dan lugar a flujos que procesan sus datos , en este caso se trata de convertir el estado de un objeto, incluyendo la clase del objeto y el prototipo de la misma en una secuencia de bytes y viceversa.
Por esta razón los flujos ObjectInputStream y ObjectOutputStream deben ser construidos sobre otros flujos que canalicen esos bytes hacia y desde el archivo, como se muestra en la siguiente figura:
gch@pumas.iingen.unam.mx
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernández
PDelValleM@iingen.unam.mx
Programa
ObjetosFlujo
ObjectInputStream
FlujoFileInputStream
FlujoObjectOutputStream
FlujoFileOutputStreamarchivo
gch@pumas.iingen.unam.mx
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernández
PDelValleM@iingen.unam.mx
¿Como seriar objetos?
Interfaz Serializable
Para poder seriar los objetos de una clase, ésta debe implementar la interfaz Serealizable.
Es una interfaz vacía, su propósito es simplemente identificar clases cuyos objetos se pueden seriar.
public class CEmpledo implements Serializable {
//cuerpo de la clase}
gch@pumas.iingen.unam.mx
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernández
PDelValleM@iingen.unam.mx
Un flujo de la clase ObjectOutputStream permite enviar datos de tipo primitivo y objetos hacia un flujo OutputStream
writeObjectMétodo que permite escribir un objeto en un flujo ObjectOutputStream. Este método lanza la excepción NotSerializableException si se intenta escribir un objeto de una clase que no implementa la interfaz Serializable.
FileOutputStream fos = new FileOutputStream (“datos.txt”);ObjectOutputStream oos = new ObjectOutputStream (fos);
oos.writeUTF(“Datos Empleados 2008”);//crea el objeto y lo almacena en el archivooos.writeObject (new CPersona(nombre,direccion,tel);
Escribir objetos en un archivo
gch@pumas.iingen.unam.mx
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernández
PDelValleM@iingen.unam.mx
Un flujo de la clase ObjectInputStream permite recuperar datos de tipo primitivo y objetos desde un flujo InputStream
readObjectMétodo que permite leer un objeto en un flujo ObjectInputStream. Si se almacenan datos primitivos y objetos, deben recuperarse en el mismo orden.
FileInputStream fis = new FileInputStream (“datos.txt”);ObjectInputStream ois = new ObjectInputStream (fis);
oos.writeUTF(“Datos Empleados 2008”);//crea el objeto y lo almacena en el archivooos.writeObject (new CPersona(nombre,direccion,tel);
Leer objetos de un archivo
gch@pumas.iingen.unam.mx
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernández
PDelValleM@iingen.unam.mx
Ejemplo:
import java.io.*;
class CPersona implements Serializable { int clave; public CPersona (int cve) { clave = cve; }
}
gch@pumas.iingen.unam.mx
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernández
PDelValleM@iingen.unam.mx
Ejemplo escrituraimport java.io.*;
class EjemSeriarObjetos { public static void main (String []args) throws IOException { BufferedReader leer = new BufferedReader (
new InputStreamReader (System.in)); FileOutputStream fos = new FileOutputStream ("datos.txt"); ObjectOutputStream oos = new ObjectOutputStream (fos); int cve; System.out.print("clave: "); cve = Integer.parseInt(leer.readLine()); System.out.println("Grabando datos ..."); oos.writeUTF("Datos de empleados 2008"); oos.writeObject( new CPersona(cve)); oos.close(); } }
gch@pumas.iingen.unam.mx
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernández
PDelValleM@iingen.unam.mx
Ejemplo lectura
import java.io.*;
class EjemDeseriarObjetos { public static void main (String []args) throws IOException { FileInputStream fis = new FileInputStream ("datos.txt"); ObjectInputStream ois = new ObjectInputStream (fis); String str; str = ois.readUTF(); try { CPersona xper = (CPersona) ois.readObject(); System.out.println("Los datos leidos son: " + str + "\t" + xper.clave); } catch (java.lang.ClassNotFoundException e) {} ois.close(); } }
top related