Sie sind auf Seite 1von 26

PDelValleM@iingen.unam.

mx

gch@pumas.iingen.unam.mx

Archivos
Secuenciales

1
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernndez

PDelValleM@iingen.unam.mx

gch@pumas.iingen.unam.mx

Archivos con tipos primitivos


Las siguientes clases permiten leer y escribir respectivamente
datos de cualquier tipo de dato primitivo

DataInputStream
Programa

fis

Archivo

dos

fos

Archivo

DataOutputStream
Programa

dis

Se crea un flujo asociado con un origen o destino de datos


Se asocia un filtro con el flujo anterior
Finalmente, el programa leer o escribir a travs de este filtro
2

Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernndez

PDelValleM@iingen.unam.mx

gch@pumas.iingen.unam.mx

Mtodos de la clase DataOutputStream

3
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernndez

PDelValleM@iingen.unam.mx

gch@pumas.iingen.unam.mx

Ejemplo escritura
//Crea los flujos de escritura
FileOutputStream fos = new FileOutputStream (tareas.txt);
DataOutputStream dos = new DataOutputStream (fos);
//escribe datos al archivo
dos.writeUTF(Juan Lpez);
dos.writeInt(3245);
dos.writeFloat(8500.00);
dos.writeLong(56221214);
//cierra los flujos
dos.close();
fos.close();
4
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernndez

PDelValleM@iingen.unam.mx

gch@pumas.iingen.unam.mx

Mtodos de la clase DataInputStream

5
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernndez

PDelValleM@iingen.unam.mx

gch@pumas.iingen.unam.mx

Ejemplo lectura
//Crea los flujos de lectura
FileInputStream 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();
6
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernndez

PDelValleM@iingen.unam.mx

gch@pumas.iingen.unam.mx

Ejemplo:
Agenda telefnica

7
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernndez

PDelValleM@iingen.unam.mx

gch@pumas.iingen.unam.mx

Ejemplo MostrarListaTfnos
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, direccin;
String telefono;

8
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernndez

PDelValleM@iingen.unam.mx

gch@pumas.iingen.unam.mx

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)));

9
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernndez

PDelValleM@iingen.unam.mx

gch@pumas.iingen.unam.mx

do
{
// Leer un nombre, una direccin y un telfono desde el
// fichero. Cuando se alcance el final del fichero Java
// lanzar una excepcin del tipo EOFException.
nombre = dis.readUTF();
direccin = dis.readUTF();
telefono = dis.readUTF();
// Mostrar los datos nombre, direccin y telfono
System.out.println(nombre);
System.out.println(direccin);
System.out.println(telefono);
System.out.println();
} while (true);
10
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernndez

PDelValleM@iingen.unam.mx

gch@pumas.iingen.unam.mx

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();
}
}
11
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernndez

PDelValleM@iingen.unam.mx

gch@pumas.iingen.unam.mx

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());
}
}
}

12
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernndez

PDelValleM@iingen.unam.mx

gch@pumas.iingen.unam.mx

Ejemplo CrearListaTfnos
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, direccin;
String telefono;

13
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernndez

PDelValleM@iingen.unam.mx

gch@pumas.iingen.unam.mx

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: ");
direccin = Teclado.cadena("Direccion:");
telefono = Teclado.cadena("Telefono: ");
// Almacenar un nombre, una direccin y un telfono en el fichero

dos.writeUTF(nombre);
dos.writeUTF(direccin);
dos.writeUTF(telefono);
resp = Teclado.entero ("desea escribir otro registro 1)si 2) no? ");

} while (resp == 1);


}
14
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernndez

PDelValleM@iingen.unam.mx

gch@pumas.iingen.unam.mx

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;

15
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernndez

PDelValleM@iingen.unam.mx

gch@pumas.iingen.unam.mx

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());
}
}
}
16
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernndez

PDelValleM@iingen.unam.mx

gch@pumas.iingen.unam.mx

Seriacin
de
Objetos

17
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernndez

PDelValleM@iingen.unam.mx

gch@pumas.iingen.unam.mx

Seriacin
La operacin de enviar una serie de objetos a un
archivo.

Deseriacin
La operacin de leer o recuperar objetos del
archivo y reconstruirlos en la memoria

Para realizar estas operaciones


automticamente, el paquete java.io proporciona
las clases
ObjectOutputStream
ObjetcInputStream

Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernndez

PDelValleM@iingen.unam.mx

gch@pumas.iingen.unam.mx

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 razn 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:
19
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernndez

PDelValleM@iingen.unam.mx

gch@pumas.iingen.unam.mx

Programa

Flujo
ObjectInputStream

Flujo
FileInputStream

Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernndez

Objetos

Flujo
ObjectOutputStream

archivo

Flujo
FileOutputStream

PDelValleM@iingen.unam.mx

gch@pumas.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 vaca, su propsito es


simplemente identificar clases cuyos objetos se
pueden seriar.
public class CEmpledo implements Serializable
{
//cuerpo de la clase
}

Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernndez

PDelValleM@iingen.unam.mx

gch@pumas.iingen.unam.mx

Escribir objetos en un archivo

Un flujo de la clase ObjectOutputStream permite enviar datos de


tipo primitivo y objetos hacia un flujo OutputStream

writeObject
Mtodo que permite escribir un objeto en un flujo
ObjectOutputStream. Este mtodo lanza la excepcin
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 archivo
oos.writeObject (new CPersona(nombre,direccion,tel);
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernndez

PDelValleM@iingen.unam.mx

gch@pumas.iingen.unam.mx

Leer objetos de un archivo

Un flujo de la clase ObjectInputStream permite recuperar


datos de tipo primitivo y objetos desde un flujo InputStream

readObject
Mtodo 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 archivo
oos.writeObject (new CPersona(nombre,direccion,tel);
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernndez

PDelValleM@iingen.unam.mx

gch@pumas.iingen.unam.mx

Ejemplo:

import java.io.*;
class CPersona implements Serializable {
int clave;
public CPersona (int cve) {
clave = cve;
}
}

Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernndez

PDelValleM@iingen.unam.mx

Ejemplo escritura

gch@pumas.iingen.unam.mx

import 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();
}
}
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernndez

PDelValleM@iingen.unam.mx

gch@pumas.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();
}
}
Ing. Patricia Del Valle Morales, M en C Gabriel Castillo Hernndez

Das könnte Ihnen auch gefallen