Utilizar Canales para Leer y Escribir Ficheros

Los canales de Ficheros son quizás los canales más fáciles de entender. Las clases FileInputStream y FileOutputStream representan una canal de entrada (o salida) sobre un fichero que reside en el sistema de ficheros nativo. Se puede crear un canal de fichero desde un nombre de fichero, un objeto File o un objeto FileDescriptor. Utiliza los canales de ficheros para leer o escribir datos de un fichero del sistema de ficheros.

Este pequeño ejemplo utiliza los canales de ficheros para copiar el contenido de un fichero en otro:

import java.io.*;

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

            FileInputStream fis = new FileInputStream(inputFile);
            FileOutputStream fos = new FileOutputStream(outputFile);
            int c;

            while ((c = fis.read()) != -1) {
               fos.write(c);
            }

            fis.close();
            fos.close();
        } catch (FileNotFoundException e) {
            System.err.println("FileStreamsTest: " + e);
        } catch (IOException e) {
            System.err.println("FileStreamsTest: " + e);
        }
    }
}
Aquí tiene el contenido del fichero de entrada farrago.txt:
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
Este programa crea un FileInputStream desde un objeto File con este código:
File inputFile = new File("farrago.txt"); 
FileInputStream fis = new FileInputStream(inputFile);
Observa el uso del objeto File inputFile en el constructor. inputFile representa el fichero llamado farrago.txt, del sistema de ficheros nativo. Este programa sólo utiliza inputFile para crear un FileInputStream sobre farrago.txt. Sin embargo, el programa podría utilizar inputFile para obtener información sobre farrago.txt como su path completo, por ejemplo.


Ozito