Java examples for java.nio:ByteBuffer Int
mapping an entire File into a ByteBuffer .
//package com.java2s; import java.io.*; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class Main { /**// w w w .j a v a2 s. c o m * This is a convenience method for mapping an entire {@link File} into a * {@link ByteBuffer}. * * @param file The {@link File} to map. * @return Returns a new {@link ByteBuffer}. * @see #map(File,long,long,FileChannel.MapMode) * @see #mapReadOnly(File) * @see #mapReadOnly(File,long,long) * @see #mapReadWrite(File) * @see #mapReadWrite(File,long,long) */ public static ByteBuffer map(File file, FileChannel.MapMode mapMode) throws IOException { return map(file, 0, file.length(), mapMode); } /** * This is a convenience method for mapping a {@link File} into a * {@link ByteBuffer}. * * @param file The {@link File} to map. * @param position The position within the file at which the mapped region * is to start. * @param size The size of the region to be mapped. * @param mapMode The {@link FileChannel.MapMode} to use. * @return Returns a new {@link ByteBuffer}. * @see #map(File,FileChannel.MapMode) * @see #mapReadOnly(File) * @see #mapReadOnly(File,long,long) * @see #mapReadWrite(File) * @see #mapReadWrite(File,long,long) */ public static ByteBuffer map(File file, long position, long size, FileChannel.MapMode mapMode) throws IOException { final String rafMode; if (mapMode == FileChannel.MapMode.READ_ONLY) rafMode = "r"; else if (mapMode == FileChannel.MapMode.READ_WRITE) rafMode = "rw"; else throw new IllegalArgumentException("unsupported MapMode"); final RandomAccessFile raf = new RandomAccessFile(file, rafMode); try { return raf.getChannel().map(mapMode, position, size); } finally { raf.close(); } } }