Professional Documents
Culture Documents
Ficheros.Para realizar operaciones sobre los ficheros, necesitamos contar con la informacin referente sobre un fichero (archivo).
Objetos FileInputStream
Los objetos FileInputStream tpicamente representan archivos de texto accedidos en orden secuencial, byte a byte.
Apertura de un FileInputStream
Para abrir un FileInputStream sobre un archivo, se le da al constructor un String o un objeto File: FileInputStream mi ArchivoSt; miArchivoSt = new FileInputStream( "/etc/kk" );
Lectura de un FileInputStream Una vez abierto el FileInputStream, se puede leer de l mtodo read()
Cierre de FileInputStream Cuando se termina con un archivo, existen dos opciones para cerrarlo: explcitamente, o implcitamente cuando se recicla el objeto
Los objetos DataInputStream se comportan como los FileInputStream. Los streams de datos pueden leer cualquiera de las variables de tipo nativo, como floats,ints o chars. Generalmente se utilizan DataInputStream con archivos binarios.
byte readByte(); int readUnsignedByte(); short readShort(); int readUnsignedShort(); char readChar(); int readInt(); long readLong(); float readFloat(); double readDouble(); String readLine()
ImputStream is; byte buffer[] = new byte[24]; is = new URL( getDocumentBase(),datos).openSt ream(); is.read( buffer,0,buffer.length );
Los objetos FileOutputStream son tiles para la escritura de archivos de texto. Como con los archivos de entrada, primero se necesita abrir el archivo para luego escribir en l.
Tenemos tres posibilidades: void write( int b );//Escribe un byte. void write( byte b[] );//Escribe todo el array, si es posible. void write( byte b[],int offset,int longitud ); //Escribe longitud bytes en b comenzando por b[offset].
FileOutputStream miFileStream; BufferdOutpurStream miBufferStream; miFileStream = new FileOutputStream( "/tmp/kk" ); miBufferStream = new BufferedOutputStream(miFileStream );
Streams DataOutput
Java tambin implementa una clase de salida complementaria a la clase DataInputStream. Con la clase DataOutputStream, se pueden escribir datos binarios en un archivo.
miBufferStream = new BufferedOutputStream( miFileStream ); miDataStream = new DataOutputStream( miBufferStream ); miBufferStream.write( b ); miDataStream.writeInt( i ); miDataStream.close(); miBufferStream.close(); miFileStream.close();
Los objetos RandomAccessFile esperan informacin de lectura/escritura de la misma manera que los objetos DataInput/DataOutput. Se tiene acceso a todas las operaciones read() y write() de las Clases DataInputStream y DataOutputStream. Tambin se tienen muchos mtodos para moverse dentro de un archivo: long getFilePointer(); Devuelve la posicin actual del puntero del archivo: void seek( long pos ); Coloca el puntero del archivo en una posicin determinada. La posicin se da como un desplazamiento en bytes desde el comienzo del archivo. La posicin 0 marca el comienzo de ese archivo: long length(); Devuelve la longitud del archivo. La posicin length() marca el final de ese archivo.
Acceso a la Informacin
RegistroCuentasAccesoAleatorio.java
import java.io; public class RegistroCuentasAccesoAleatorio extends RegistroCuentas { public static final int TAMANIO = 72; public RegistroCuentasAccesoAleatorio() { this( 0, "", "", 0.0 ); } public RegistroCuentasAccesoAleatorio( int cuenta, String primerNombre, String apellidoPaterno, double saldo ) { super( cuenta, primerNombre, apellidoPaterno, saldo ); } public void leer( RandomAccessFile archivo ) throws IOException { establecerCuenta( archivo.readInt() ); establecerPrimerNombre( leerNombre( archivo ) );
establecerApellidoPaterno( leerNombre( archivo ) ); establecerSaldo( archivo.readDouble() ); } private String leerNombre( RandomAccessFile archivo ) throws IOException { char nombre[] = new char[ 15 ], temp; for ( int cuenta = 0; cuenta < nombre.length; cuenta++ ) { temp = archivo.readChar(); nombre[ cuenta ] = temp; } return new String( nombre ).replace( '\0', ' ' );
public void escribir( RandomAccessFile archivo ) throws IOException { archivo.writeInt( obtenerCuenta() ); escribirNombre( archivo, obtenerPrimerNombre() ); escribirNombre( archivo, obtenerApellidoPaterno() ); archivo.writeDouble( obtenerSaldo() ); }
private void escribirNombre( RandomAccessFile archivo, String nombre ) throws IOException { StringBuffer bufer = null; if ( nombre != null ) bufer = new StringBuffer( nombre ); else bufer = new StringBuffer( 15 ); bufer.setLength( 15 ); archivo.writeChars( bufer.toString() );