Import java. Io. fileinputstream;
Import java. Io. filenotfoundexception;
Import java. Io. ioexception;
Import java. Io. randomaccessfile;
Import java. NiO. bytebuffer;
Import java. NiO. mappedbytebuffer;
Import java. NiO. channels. filechannel;
Import java. NiO. channels. readablebytechannel;
Public class test {
// Static int length = 0x8ffffff; // 128 MB
Static int length = 0 xfffffff ;//
Public static void main (string [] ARGs) throws exception {
Test T = new test ();
T. testbytebufferread ();
T. tew.appedbytebufferread ();
}
Public void testbytebufferread (){
Try {
Int length = 0 xfffffff;
Mappedbytebuffer out = NULL;
Try {
Out = new randomaccessfile ("C:/test. dat", "RW"). getchannel ()
. Map (filechannel. mapmode. read_write, 0, length );
For (INT I = 0; I <length; I ++)
Out. Put (byte) 'X ');
System. Out. println ("finished writing ");
} Catch (filenotfoundexception e ){
E. printstacktrace ();
} Catch (ioexception e ){
E. printstacktrace ();
}
// Obtain a channel
Readablebytechannel channel = new fileinputstream ("C:/test. dat ")
. Getchannel ();
// Create a direct bytebuffer; see also e158 creating a bytebuffer
Bytebuffer Buf = bytebuffer. allocatedirect (10 );
Int numread = 0;
While (numread> = 0 ){
// Read () places read bytes at the buffer's position so
// Position shoshould always be properly set before calling read ()
// This method sets the position to 0
Buf. Rewind ();
// Read bytes from the Channel
Numread = channel. Read (BUF );
// The read () method also moves the position so in order
// Read the new bytes, the buffer's position must be set back
// 0
Buf. Rewind ();
// Read bytes from bytebuffer; see also
// E159 getting bytes from a bytebuffer
For (INT I = 0; I <10; I ++ ){
Byte B = Buf. Get (I );
System. Out. println (char) B );
}
}
} Catch (exception e ){
E. printstacktrace ();
}
}
Public void teid appedbytebufferread (){
Int length = 0 xfffffff;
Mappedbytebuffer out = NULL;
Try {
Out = new randomaccessfile ("C:/test. dat", "RW"). getchannel (). Map (
Filechannel. mapmode. read_write, 0, length );
For (INT I = 0; I <length; I ++)
Out. Put (byte) 'X ');
System. Out. println ("finished writing ");
} Catch (filenotfoundexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
} Catch (ioexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
For (INT I = length/2; I <length/2 + 6; I ++)
System. Out. Print (char) Out. Get (I); // Read File
}
}