java.nio.channels.FileChannel.map()方法的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(9.0k)|赞(0)|评价(0)|浏览(201)

本文整理了Java中java.nio.channels.FileChannel.map()方法的一些代码示例,展示了FileChannel.map()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。FileChannel.map()方法的具体详情如下:
包路径:java.nio.channels.FileChannel
类名称:FileChannel
方法名:map

FileChannel.map介绍

[英]Maps the file into memory. There can be three modes: read-only, read/write and private. After mapping, changes made to memory or the file channel do not affect the other storage place.

Note: mapping a file into memory is usually expensive.
[中]将文件映射到内存中。可以有三种模式:只读、读/写和专用。映射后,对内存或文件通道所做的更改不会影响其他存储位置。
注意:将文件映射到内存通常是昂贵的。

代码示例

代码示例来源:origin: apache/kafka

/**
 * Attempt to read a file as a string
 * @throws IOException
 */
public static String readFileAsString(String path, Charset charset) throws IOException {
  if (charset == null) charset = Charset.defaultCharset();
  try (FileChannel fc = FileChannel.open(Paths.get(path))) {
    MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
    return charset.decode(bb).toString();
  }
}

代码示例来源:origin: google/guava

private static MappedByteBuffer mapInternal(File file, MapMode mode, long size)
  throws IOException {
 checkNotNull(file);
 checkNotNull(mode);
 Closer closer = Closer.create();
 try {
  RandomAccessFile raf =
    closer.register(new RandomAccessFile(file, mode == MapMode.READ_ONLY ? "r" : "rw"));
  FileChannel channel = closer.register(raf.getChannel());
  return channel.map(mode, 0, size == -1 ? channel.size() : size);
 } catch (Throwable e) {
  throw closer.rethrow(e);
 } finally {
  closer.close();
 }
}

代码示例来源:origin: aragozin/jvm-tools

MemoryMappedData(RandomAccessFile file, long length)
     throws IOException {
  FileChannel channel = file.getChannel();
  buf = channel.map(MAP_MODE, 0, length);
  channel.close();
}

代码示例来源:origin: twitter/ambrose

public static String readFile(String path) throws IOException {
 FileInputStream stream = new FileInputStream(new File(path));
 try {
  FileChannel fc = stream.getChannel();
  MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
  return Charset.defaultCharset().decode(bb).toString();
 } finally {
  stream.close();
 }
}

代码示例来源:origin: apache/mahout

public void setData(File f, boolean loadNow) throws IOException {
 Preconditions.checkArgument(f.length() == rows * columns * 8L, "File " + f + " is wrong length");
 for (int i = 0; i < (rows + rowsPerBlock - 1) / rowsPerBlock; i++) {
  long start = i * rowsPerBlock * columns * 8L;
  long size = rowsPerBlock * columns * 8L;
  MappedByteBuffer buf = new FileInputStream(f).getChannel().map(FileChannel.MapMode.READ_ONLY, start,
                                  Math.min(f.length() - start, size));
  if (loadNow) {
   buf.load();
  }
  addData(buf.asDoubleBuffer());
 }
}

代码示例来源:origin: stackoverflow.com

MappedByteBuffer mem =
 new RandomAccessFile("/tmp/mapped.txt", "rw").getChannel()
 .map(FileChannel.MapMode.READ_WRITE, 0, 1);

while(true){
 while(mem.get(0)!=5) Thread.sleep(0); // waiting for client request
 mem.put(0, (byte)10); // sending the reply
}

代码示例来源:origin: stackoverflow.com

final File             file;
 final FileChannel      channel;
 final MappedByteBuffer buffer;
 file    = new File(fileName);
 fin     = new FileInputStream(file);
 channel = fin.getChannel();
 buffer  = channel.map(MapMode.READ_ONLY, 0, file.length());

代码示例来源:origin: smuyyh/BookReader

ByteBuffer fbuf = f.getChannel().map(
    FileChannel.MapMode.READ_ONLY, 0, f.length());
f.seek(0);
InputStream bin = new FileInputStream(f.getFD());
BufferedReader in = new BufferedReader(new InputStreamReader(
    bin));

代码示例来源:origin: aragozin/jvm-tools

HprofMappedByteBuffer(File dumpFile) throws IOException {
  FileInputStream fis = new FileInputStream(dumpFile);
  FileChannel channel = fis.getChannel();
  length = channel.size();
  dumpBuffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, length);
  channel.close();
  readHeader();
}

代码示例来源:origin: WVector/AppUpdate

public static String getFileMD5(File file) {
  if (!file.exists()) {
    return "";
  }
  FileInputStream in = null;
  try {
    in = new FileInputStream(file);
    FileChannel channel = in.getChannel();
    MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
    MessageDigest md = MessageDigest.getInstance("MD5");
    md.update(buffer);
    return bytes2Hex(md.digest());
  } catch (NoSuchAlgorithmException | IOException e) {
    e.printStackTrace();
  } finally {
    if (in != null) {
      try {
        in.close();
      } catch (IOException ignored) {
      }
    }
  }
  return "";
}

代码示例来源:origin: prestodb/presto

public static Slice mapFileReadOnly(File file)
      throws IOException
  {
    requireNonNull(file, "file is null");

    if (!file.exists()) {
      throw new FileNotFoundException(file.toString());
    }

    try (RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
        FileChannel channel = randomAccessFile.getChannel()) {
      MappedByteBuffer byteBuffer = channel.map(MapMode.READ_ONLY, 0, file.length());
      return wrappedBuffer(byteBuffer);
    }
  }
}

代码示例来源:origin: real-logic/agrona

/**
 * Check that file exists, open file, and return MappedByteBuffer for entire file
 * <p>
 * The file itself will be closed, but the mapping will persist.
 *
 * @param location         of the file to map
 * @param descriptionLabel to be associated for any exceptions
 * @return {@link java.nio.MappedByteBuffer} for the file
 */
public static MappedByteBuffer mapExistingFile(final File location, final String descriptionLabel)
{
  checkFileExists(location, descriptionLabel);
  MappedByteBuffer mappedByteBuffer = null;
  try (RandomAccessFile file = new RandomAccessFile(location, "rw");
    FileChannel channel = file.getChannel())
  {
    mappedByteBuffer = channel.map(READ_WRITE, 0, channel.size());
  }
  catch (final IOException ex)
  {
    LangUtil.rethrowUnchecked(ex);
  }
  return mappedByteBuffer;
}

代码示例来源:origin: real-logic/simple-binary-encoding

public IrDecoder(final String fileName)
{
  try
  {
    channel = FileChannel.open(Paths.get(fileName), READ);
    final long fileLength = channel.size();
    final MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, fileLength);
    directBuffer = new UnsafeBuffer(buffer);
    length = fileLength;
    offset = 0;
  }
  catch (final IOException ex)
  {
    throw new RuntimeException(ex);
  }
}

代码示例来源:origin: atomix/atomix

private static MappedByteBuffer mapFile(RandomAccessFile randomAccessFile, int offset, int size, FileChannel.MapMode mode) {
 try {
  return randomAccessFile.getChannel().map(mode, offset, size);
 } catch (IOException e) {
  throw new RuntimeException(e);
 }
}

代码示例来源:origin: aragozin/jvm-tools

HprofLongMappedByteBuffer(File dumpFile) throws IOException {
  FileInputStream fis = new FileInputStream(dumpFile);
  FileChannel channel = fis.getChannel();
  length = channel.size();
  dumpBuffer = new MappedByteBuffer[(int) (((length + BUFFER_SIZE) - 1) / BUFFER_SIZE)];
  for (int i = 0; i < dumpBuffer.length; i++) {
    long position = i * BUFFER_SIZE;
    long size = Math.min(BUFFER_SIZE + BUFFER_EXT, length - position);
    dumpBuffer[i] = channel.map(FileChannel.MapMode.READ_ONLY, position, size);
  }
  channel.close();
  readHeader();
}

代码示例来源:origin: jiangqqlmj/FastDev4Android

MessageDigest algorithm = MessageDigest.getInstance("MD5");
algorithm.reset();
in = new FileInputStream(file);
FileChannel ch = in.getChannel();
MappedByteBuffer byteBuffer;
byteBuffer = ch
    .map(FileChannel.MapMode.READ_ONLY, 0, file.length());
algorithm.update(byteBuffer);
return toHexString(algorithm.digest(), "");

代码示例来源:origin: SonarSource/sonarqube

public AllProcessesCommands(File directory) {
 if (!directory.isDirectory() || !directory.exists()) {
  throw new IllegalArgumentException("Not a valid directory: " + directory);
 }
 try {
  sharedMemory = new RandomAccessFile(new File(directory, "sharedmemory"), "rw");
  mappedByteBuffer = sharedMemory.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, MAX_SHARED_MEMORY);
 } catch (IOException e) {
  throw new IllegalArgumentException("Unable to create shared memory : ", e);
 }
}

代码示例来源:origin: stackoverflow.com

File pdfFile = new File("/path/to/pdf.pdf");
RandomAccessFile raf = new RandomAccessFile(pdfFile, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
PDFFile pdf = new PDFFile(buf);
PDFPage page = pdf.getPage(0);

// create the image
Rectangle rect = new Rectangle(0, 0, (int) page.getBBox().getWidth(),
                 (int) page.getBBox().getHeight());
BufferedImage bufferedImage = new BufferedImage(rect.width, rect.height,
                 BufferedImage.TYPE_INT_RGB);

Image image = page.getImage(rect.width, rect.height,    // width & height
              rect,                       // clip rect
              null,                       // null for the ImageObserver
              true,                       // fill background with white
              true                        // block until drawing is done
);
Graphics2D bufImageGraphics = bufferedImage.createGraphics();
bufImageGraphics.drawImage(image, 0, 0, null);
ImageIO.write(bufferedImage, format, new File( "/path/to/image.jpg" ));

代码示例来源:origin: real-logic/agrona

public static MappedByteBuffer waitForFileMapping(
  final Consumer<String> logger,
  final File markFile,
  final long deadlineMs,
  final EpochClock epochClock)
{
  try (FileChannel fileChannel = FileChannel.open(markFile.toPath(), READ, WRITE))
  {
    while (fileChannel.size() < 4)
    {
      if (epochClock.time() > deadlineMs)
      {
        throw new IllegalStateException("Mark file is created but not populated");
      }
      sleep(16);
    }
    if (null != logger)
    {
      logger.accept("INFO: Mark file exists: " + markFile);
    }
    return fileChannel.map(READ_WRITE, 0, fileChannel.size());
  }
  catch (final IOException ex)
  {
    throw new IllegalStateException("cannot open mark file for reading", ex);
  }
}

代码示例来源:origin: aragozin/jvm-tools

LongMemoryMappedData(RandomAccessFile file, long length)
     throws IOException {
  FileChannel channel = file.getChannel();
  dumpBuffer = new MappedByteBuffer[(int) (((length + BUFFER_SIZE) - 1) / BUFFER_SIZE)];
  for (int i = 0; i < dumpBuffer.length; i++) {
    long position = i * BUFFER_SIZE;
    long size = Math.min(BUFFER_SIZE + BUFFER_EXT, length - position);
    dumpBuffer[i] = channel.map(MemoryMappedData.MAP_MODE, position, size);
  }
  channel.close();
}

相关文章