Ver Mensaje Individual
  #2 (permalink)  
Antiguo 23/10/2007, 12:12
clinisbut
 
Fecha de Ingreso: diciembre-2004
Mensajes: 278
Antigüedad: 19 años, 5 meses
Puntos: 0
Re: Duda con FileChannel.compact()

Pongo aquí el codigo al completo, por si ayuda a ver su "logica".
Código:
File aFile = new File( "C:/texto.txt" );
FileInputStream inFile = new FileInputStream( aFile );
FileChannel inChannel = inFile.getChannel();
try
{
	ByteBuffer buf = ByteBuffer.allocateDirect( 1024 );
	buf.position( buf.limit() );			//Ponemos la posición para el bucle.
	int strLength = 0;						//Longitud del string
	byte[] strChars = null;					//Array para el string

	while( true )
	{
		if( buf.remaining() < 8 )			//Si no hay suficiente para almacenar un double
		{	//... compactamos y leemos
			if( inChannel.read( buf.compact() ) == -1 )
				break;	//Si ya no queda nada que leer, nos vamos
			buf.flip();	//limit=position 	Position=0;
		}
		strLength = (int)buf.getDouble();
		
				
		//Verificamos que quedan suficientes bytes para un string completo
		if( buf.remaining() < strLength*2 )	//Si no hay suficientes para almacenar un string
		{	//Compactamos...
			if( inChannel.read( buf.compact() ) == -1 )		//Si hemos llegado a final de fichero...
				break;	//Nos vamos
			buf.flip();
		}				
		strChars = new byte[2*strLength];
		buf.get( strChars );


		if( buf.remaining() < 8 )	//Verificamos que queda suficiente espacio para el primo
		{
			if( inChannel.read( buf.compact() ) == -1 )
				break;
			buf.flip();
		}
			
		System.out.printf( " String length: %3s String: % -12s Binari value: %3d%n", strLength, ByteBuffer.wrap( strChars ).asCharBuffer(), buf.getLong() );
	}
}
No pretendo que me expliquen que hace, pues eso ya lo se. Únicamente quiero entender esas líneas que dije.