Read file via ReadableByteChannel - Java java.nio.channels

Java examples for java.nio.channels:ReadableByteChannel

Description

Read file via ReadableByteChannel

Demo Code



import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;

public class ReadWithChannel {

    public static void main(String[] args) {
        try (ReadableByteChannel channel = new FileInputStream("input.txt")
                .getChannel()) {//w ww  .j  a  v a 2  s  .  co m
            ByteBuffer buf = ByteBuffer.allocateDirect(8);

            int bytesRead = 0;
            while (bytesRead >= 0) {
                bytesRead = channel.read(buf);
                buf.flip();
                for (int i = 0; i < bytesRead; i++) {
                    byte b = buf.get();
                    System.out.print((char) b);

                }
            }

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

    }

}

Related Tutorials