Java Files create SeekableByteChannel

Description

Java Files create SeekableByteChannel

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) {
      int bufferSize = 8;
      Path path = Paths.get("Main.java");

      try (SeekableByteChannel sbc = Files.newByteChannel(path)) {
         ByteBuffer buffer = ByteBuffer.allocate(bufferSize);

         sbc.position(4);//from  w ww.  j av  a  2  s.co m
         sbc.read(buffer);
         for (int i = 0; i < 5; i++) {
            System.out.print((char) buffer.get(i));
         }
         System.out.println();

         buffer.clear();
         sbc.position(0);
         sbc.read(buffer);
         for (int i = 0; i < 4; i++) {
            System.out.print((char) buffer.get(i));
         }
         System.out.println();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}



PreviousNext

Related