I/O: Leer y Escibir

Los streams de ficheros son quiz�s los m�s f�ciles de entender. Simplemente ponemos, el stream de ficheros --FileReader, FileWriter, FileInputStream, y FileOutputStream-- cada uno de lectura o escritura sobre un fichero del sistema de ficheros nativo.

Podemos crear un stream de fichero desde un nombre de fichero en el formato de un string, desde un objeto File, o desde un objeto FileDescriptor.

El siguiente programa Copy usa FileReader y FileWriter para copiar el contenido de un fichero llamado farrago.txt en otro fichero llamado outagain.txt.

import java.io.*;

public class Copy {
    public static void main(String[] args) throws IOException {
	File inputFile = new File("farrago.txt");
	File outputFile = new File("outagain.txt");

        FileReader in = new FileReader(inputFile);
        FileWriter out = new FileWriter(outputFile);
        int c;

        while ((c = in.read()) != -1)
           out.write(c);

        in.close();
        out.close();
    }
}

Este programa es muy sencillo.

Abre FileReader sobre farrago.txt y abre FileWriter sobre outagain.txt.

El programa lee caracteres desde el reader mientras haya m�s entradas en el fichero de entrada.

Cuando la entrada se acada, el programa cierra tanto el reader como el writer.

Observa el c�digo que usa el programa Copy para crear un FileReader.

File inputFile = new File("farrago.txt"); 
FileReader in = new FileReader(inputFile);

Este c�digo crea un objeto File que representa el fichero nombrado en el sistema de ficheros nativo. File es una clase de utilidad proporcionada por java.io. Este programa usa este objeto s�lo para construir un FileReader sobre farrago.txt.

Sin embargo, se podr�a usar inputFile para obtener informaci�n sobre farrago.txt, como su path completo.

Despu�s de haber ejecutado el programa, deber�amos encontrar una copia exacta de farrago.txt en un fichero llamado outagain.txt en el mismo directorio. Aqu� est� el contenido del fichero:

So she went into the garden to cut a cabbage-leaf, to
make an apple-pie; and at the same time a great
she-bear, coming up the street, pops its head into the
shop. 'What! no soap?' So he died, and she very
imprudently married the barber; and there were
present the Picninnies, and the Joblillies, and the
Garyalies, and the grand Panjandrum himself, with the
little round button at top, and they all fell to playing
the game of catch as catch can, till the gun powder ran
out at the heels of their boots.

Samuel Foote 1720-1777

Recuerda que FileReader y FileWriter leen y escriben caracteres de 16 bits. Sin embargo, la mayor�a del sistemas de ficheros nativos est�n basados en bytes de 8 bits. Estos streams codifican los caracteres seg�n operan de acuerdo al esquema de codificaci�n de caracteres por defecto. Podemos encontrar la codificaci�n de caracteres por defecto usando System.getProperty("file.encoding"). Para especificar otra codificaci�n, deber�amos construir un OutputStreamWriter sobre un FileOutputStream y especificarla. Para m�s informaci�n sobre la codificaci�n de caracteres puedes ver la secci�n Internationalization.

Para curiosos, aqu� tenemos otra versi�n de este programa, CopyBytes, que usa FileInputStream y FileOutputStream en lugar de FileReader y FileWriter.

COMPARTE ESTE ARTÍCULO

COMPARTIR EN FACEBOOK
COMPARTIR EN TWITTER
COMPARTIR EN LINKEDIN
COMPARTIR EN WHATSAPP
ARTÍCULO ANTERIOR

SIGUIENTE ARTÍCULO