集册 Java实例教程 将通道的文件区域直接映射到内存

将通道的文件区域直接映射到内存

欢马劈雪     最近更新时间:2020-01-02 10:19:05

665
将通道的文件区域直接映射到内存
/**
来 自 时 代      J a v a   公   众 号 - nowjava.com
**/

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)))) {

        /**
        来 自 时代Java - N o w  J a v a . c o m
        **/

      buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0,

          fileChannel.size());


    } catch (IOException ex) {

      System.err.println(ex);

    }


    if (buffer != null) {

      try {

        Charset charset = Charset.defaultCharset();

        CharsetDecoder decoder = charset.newDecoder();
展开阅读全文