package com.mindprod.example;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* Example use of java.nio to read a file.
* Requires a test file of approximately 29K called E:\temp\tempin.txt
* <p/>
* composed with IntelliJ IDEA
*
* @author Roedy Green, Canadian Mind Products
* @version 1.0
*/
public class TestNioRead
{
/**
* read some raw bytes from a file
*
* @throws IOException if problems with read
*/
@SuppressWarnings( { "UnusedAssignment" } )
private static void readRawBytes() throws IOException
{
final FileInputStream fis = new FileInputStream( "E:/temp/tempin.txt" );
FileChannel fc = fis.getChannel();
ByteBuffer buffer = ByteBuffer.allocate( 1024 * 15 );
showStats( "newly allocated read", fc, buffer );
int bytesRead = fc.read( buffer );
showStats( "after first read", fc, buffer );
showStats( "before flip", fc, buffer );
buffer.flip();
showStats( "after flip", fc, buffer );
byte[] receive = new byte[1024];
buffer.get( receive );
showStats( "after first get", fc, buffer );
buffer.get( receive );
showStats( "after second get", fc, buffer );
buffer.clear();
showStats( "after clear", fc, buffer );
bytesRead = fc.read( buffer );
showStats( "after second read", fc, buffer );
showStats( "before flip", fc, buffer );
buffer.flip();
showStats( "after flip", fc, buffer );
fc.close();
}
/**
* Display state of channel/buffer.
*
* @param where description of where we are in the program to label the state snapzhot
* @param fc FileChannel reading/writing.
* @param b Buffer to display state of:
* @throws IOException if i/o problems.
*/
private static void showStats( String where, FileChannel fc, Buffer b ) throws IOException
{
System.out
.println( where +
" channelPosition: " +
fc.position() +
" bufferPosition: " +
b.position() +
" limit: " +
b.limit() +
" remaining: " +
b.remaining() +
" capacity: " +
b.capacity() );
}
/**
* test harness
*
* @param args not used
* @throws IOException if problems reading.
*/
public static void main( String[] args ) throws IOException
{
readRawBytes();
}
}