Java SeekableByteChannel get position

Description

Java SeekableByteChannel get position

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

public class Main {

   public static void main(String[] args) {
      Path path = Paths.get("Main.java");

      final String newLine = System.getProperty("line.separator");
      try (SeekableByteChannel sbc = Files.newByteChannel(path, StandardOpenOption.WRITE)) {
         ByteBuffer buffer;//  w  w w  .  j  ava  2s  . c o  m
         long position = sbc.size();
         sbc.position(position);
         System.out.println("Position: " + sbc.position());

         buffer = ByteBuffer.wrap((newLine + "CSS").getBytes());
         sbc.write(buffer);
         System.out.println("Position: " + sbc.position());
         buffer = ByteBuffer.wrap((newLine + "HTML").getBytes());
         sbc.write(buffer);
         System.out.println("Position: " + sbc.position());
         buffer = ByteBuffer.wrap((newLine + "Java").getBytes());
         sbc.write(buffer);
         System.out.println("Position: " + sbc.position());
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}



PreviousNext

Related