Java SeekableByteChannel read and write

Description

Java SeekableByteChannel read and write

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.charset.Charset;
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) throws Exception {
    Path src = Paths.get("Main.txt");
    Charset cs = Charset.forName("UTF-8");

    try (SeekableByteChannel seekableChannel = Files.newByteChannel(src, StandardOpenOption.READ,
        StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {

      System.out.println("Before writing data: Size = " + seekableChannel.size() + ", Position = " + seekableChannel.position());

      CharBuffer charBuffer = CharBuffer.wrap("test from demo2s.com");
      // Encode the char buffer data into a byte buffer
      ByteBuffer byteBuffer = cs.encode(charBuffer);
      // Write the data to the file
      seekableChannel.write(byteBuffer);


      System.out.println("After writing data: Size = " + seekableChannel.size() + ", Position = " + seekableChannel.position());

      //To read the data from the beginning 
      //Reset the position of the SeekableByteChannel to 0,
      seekableChannel.position(0);// w w  w  .  ja  v a 2s. c  o  m

      System.out.println("After resetting position to 0" + ": Size = " + seekableChannel.size() + ", Position = " + seekableChannel.position());

      byteBuffer = ByteBuffer.allocate(128);

      while (seekableChannel.read(byteBuffer) > 0) {
        byteBuffer.rewind();
        charBuffer = cs.decode(byteBuffer);
        System.out.print(charBuffer);
        byteBuffer.flip();
      }

      System.out.println("After reading data: Size = " + seekableChannel.size() + ", Position = " + seekableChannel.position());

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}



PreviousNext

Related