Using the SeekableByteChannel Interface for Random Access to Files - Java File Path IO

Java examples for File Path IO:File Channel

Introduction

StandardOpenOption enum constants defines the following value.

Value Meaning
READ Opens file for read access
WRITE Opens file for write access
CREATECreates a new file if it does not exist
CREATE_NEWCreates a new file, failing with an exception if the file already exists
APPPEND Appends data to the end of the file (used with WRITE and CREATE)
DELETE_ON_CLOSE Deletes the file when the stream is closed (used for deleting temporary files)
TRUNCATE_EXISTING Truncates the file to 0 bytes (used with the WRITE option)
SPARSECauses the newly created file to be sparse
SYNC Keeps the file content and metadata synchronized with the underlying storage device
DSYNC Keeps the file content synchronized with the underlying storage device

Reading a File with SeekableByteChannel

Demo Code

import java.io.IOException;
import java.nio.ByteBuffer;
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;
import java.util.EnumSet;

public class Main {
  public static void main(String[] args) {
    Path path = Paths.get("C:/folder1/folder0/folder8", "story.txt");
    try (SeekableByteChannel seekableByteChannel = Files.newByteChannel(path,
        EnumSet.of(StandardOpenOption.READ))) {

      ByteBuffer buffer = ByteBuffer.allocate(12);
      String encoding = System.getProperty("file.encoding");
      buffer.clear();/*from   ww  w .  j  a  va 2  s  .  c  o  m*/

      while (seekableByteChannel.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