Mapping a Channel's File Region Directly into Memory - Java File Path IO

Java examples for File Path IO:File Channel

Description

Mapping a Channel's File Region Directly into Memory

Demo Code

import java.io.IOException;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
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/folder2/folder4", "test.txt");
    MappedByteBuffer buffer = null;

    try (FileChannel fileChannel = (FileChannel.open(path,
        EnumSet.of(StandardOpenOption.READ)))) {

      buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0,
          fileChannel.size());//w w w .j  ava  2 s.  c  o  m

    } catch (IOException ex) {
      System.err.println(ex);
    }

    if (buffer != null) {
      try {
        Charset charset = Charset.defaultCharset();
        CharsetDecoder decoder = charset.newDecoder();
        CharBuffer charBuffer = decoder.decode(buffer);
        String content = charBuffer.toString();
        System.out.println(content);

        buffer.clear();
      } catch (CharacterCodingException ex) {
        System.err.println(ex);
      }
    }
  }
}

Result


Related Tutorials