Java SeekableByteChannel class

Description

Java SeekableByteChannel class

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {
   public static void main(String args[]) throws Exception {
      int count;/*from  w  w  w. j a  v a2s. c  o  m*/
      Path filepath = null;

      filepath = Paths.get("test.txt");

      try (SeekableByteChannel fChan = Files.newByteChannel(filepath)) {
   
         ByteBuffer mBuf = ByteBuffer.allocate(128);
         do {
            // Read a buffer.
            count = fChan.read(mBuf);
            if (count != -1) {
               mBuf.rewind();
               for (int i = 0; i < count; i++){
                  System.out.print((char) mBuf.get());
               }
            }
         } while (count != -1);
         System.out.println();
      } catch (IOException e) {
         System.out.println("I/O Error " + e);
      }
   }
}



PreviousNext

Related