Reading a File with the Old ReadableByteChannel Interface - Java File Path IO

Java examples for File Path IO:File Channel

Description

Reading a File with the Old ReadableByteChannel Interface

Demo Code

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {

  public static void main(String[] args) {

    Path path = Paths.get("C:/folder1/folder0/folder8", "story.txt");

    // read a file using ReadableByteChannel
    try (ReadableByteChannel readableByteChannel = Files.newByteChannel(path)) {
      ByteBuffer buffer = ByteBuffer.allocate(12);
      buffer.clear();//from   w w w.  j a  v  a  2 s. c  om
      String encoding = System.getProperty("file.encoding");

      while (readableByteChannel.read(buffer) > 0) {
        buffer.flip();
        System.out.print(Charset.forName(encoding).decode(buffer));
        buffer.clear();
      }
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
}

Result


Related Tutorials