Example usage for java.nio.channels FileChannel map

List of usage examples for java.nio.channels FileChannel map

Introduction

In this page you can find the example usage for java.nio.channels FileChannel map.

Prototype

public abstract MappedByteBuffer map(MapMode mode, long position, long size) throws IOException;

Source Link

Document

Maps a region of this channel's file directly into memory.

Usage

From source file:com.aliyun.oss.integrationtests.TestUtils.java

public static String genRandomLengthFile() throws IOException {
    ensureDirExist(TestBase.UPLOAD_DIR);
    String filePath = TestBase.UPLOAD_DIR + System.currentTimeMillis();
    RandomAccessFile raf = new RandomAccessFile(filePath, "rw");
    FileChannel fc = raf.getChannel();

    long fileLength = rand.nextInt(MAX_RANDOM_LENGTH);
    MappedByteBuffer mbb = fc.map(MapMode.READ_WRITE, 0, fileLength);
    try {/*from   ww  w. j  av a 2 s  .c om*/
        for (int i = 0; i < fileLength; i++) {
            mbb.put(pickupAlphabet());
        }
        return filePath;
    } finally {
        if (fc != null) {
            fc.close();
        }

        if (raf != null) {
            raf.close();
        }
    }
}

From source file:com.taobao.android.tpatch.utils.MD5Util.java

public synchronized static String getFileMD5String(File file) throws IOException {
    FileInputStream in = null;/* w  ww. ja v  a 2 s. c o  m*/
    try {
        in = new FileInputStream(file);
        FileChannel ch = in.getChannel();
        MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
        messagedigest.update(byteBuffer);
        return bufferToHex(messagedigest.digest());
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:net.darkmist.alib.io.BufferUtil.java

public static ByteBuffer map(File file) throws IOException {
    FileInputStream fin = null;//from ww  w.j  a va 2s .co  m
    FileChannel fc = null;

    try {
        fin = new FileInputStream(file);
        fc = fin.getChannel();
        return fc.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
    } finally {
        fc = Closer.close(fc);
        fin = Closer.close(fin);
    }
}

From source file:org.sakaiproject.emailtemplateservice.service.impl.EmailTemplateServiceImpl.java

private static String readFile(String path) throws IOException {
    FileInputStream stream = new FileInputStream(new File(path));
    try {/*from w w w .ja  va2 s. co  m*/
        FileChannel fc = stream.getChannel();
        MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
        /* Instead of using default, pass in a decoder. */
        return Charset.defaultCharset().decode(bb).toString();
    } finally {
        stream.close();
    }
}

From source file:net.darkmist.alib.io.BufferUtil.java

public static ByteBuffer mapOrSlurp(File file) throws IOException {
    FileInputStream fin = null;// ww  w. jav  a2 s . c o  m
    FileChannel fc = null;

    try {
        fin = new FileInputStream(file);
        try {
            fc = fin.getChannel();
            return fc.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
        } catch (IOException e) {
            logger.debug("Ignoring IOException caught trying to map file {}", file, e);
        }
        return asBuffer(fin);
    } finally {
        fc = Closer.close(fc);
        fin = Closer.close(fin);
    }
}

From source file:com.gsbabil.antitaintdroid.UtilityFunctions.java

/**
 * Source://from w  ww  .j  a va  2 s .c om
 * http://stackoverflow.com/questions/4349075/bitmapfactory-decoderesource
 * -returns-a-mutable-bitmap-in-android-2-2-and-an-immu
 * 
 * Converts a immutable bitmap to a mutable bitmap. This operation doesn't
 * allocates more memory that there is already allocated.
 * 
 * @param imgIn
 *            - Source image. It will be released, and should not be used
 *            more
 * @return a copy of imgIn, but immutable.
 */
public static Bitmap convertBitmapToMutable(Bitmap imgIn) {
    try {
        // this is the file going to use temporally to save the bytes.
        // This file will not be a image, it will store the raw image data.
        File file = new File(MyApp.context.getFilesDir() + File.separator + "temp.tmp");

        // Open an RandomAccessFile
        // Make sure you have added uses-permission
        // android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        // into AndroidManifest.xml file
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");

        // get the width and height of the source bitmap.
        int width = imgIn.getWidth();
        int height = imgIn.getHeight();
        Config type = imgIn.getConfig();

        // Copy the byte to the file
        // Assume source bitmap loaded using options.inPreferredConfig =
        // Config.ARGB_8888;
        FileChannel channel = randomAccessFile.getChannel();
        MappedByteBuffer map = channel.map(MapMode.READ_WRITE, 0, imgIn.getRowBytes() * height);
        imgIn.copyPixelsToBuffer(map);
        // recycle the source bitmap, this will be no longer used.
        imgIn.recycle();
        System.gc();// try to force the bytes from the imgIn to be released

        // Create a new bitmap to load the bitmap again. Probably the memory
        // will be available.
        imgIn = Bitmap.createBitmap(width, height, type);
        map.position(0);
        // load it back from temporary
        imgIn.copyPixelsFromBuffer(map);
        // close the temporary file and channel , then delete that also
        channel.close();
        randomAccessFile.close();

        // delete the temporary file
        file.delete();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return imgIn;
}

From source file:org.bibsonomy.lucene.util.generator.LuceneGenerateResourceIndex.java

/**
 * Fast & simple file copy./*from  w  ww .  j  av  a 2  s  .c om*/
 * 
 * @param source 
 * @param dest 
 * @throws IOException 
 */
public static void copyFile(final File source, final File dest) throws IOException {
    FileChannel in = null, out = null;
    try {
        in = new FileInputStream(source).getChannel();
        out = new FileOutputStream(dest).getChannel();

        final long size = in.size();
        final MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size);

        out.write(buf);

    } finally {
        if (in != null)
            in.close();
        if (out != null)
            out.close();
    }
}

From source file:org.grouplens.lenskit.data.dao.packed.BinaryRatingDAO.java

/**
 * Open a binary rating DAO./* w  w w.  jav a 2  s  .c  o m*/
 * @param file The file to open.
 * @return A DAO backed by {@code file}.
 * @throws IOException If there is
 */
public static BinaryRatingDAO open(File file) throws IOException {
    FileInputStream input = new FileInputStream(file);
    try {
        FileChannel channel = input.getChannel();
        BinaryHeader header = BinaryHeader.read(channel);
        logger.info("Loading DAO with {} ratings of {} items from {} users", header.getRatingCount(),
                header.getItemCount(), header.getUserCount());

        ByteBuffer data = channel.map(FileChannel.MapMode.READ_ONLY, channel.position(),
                header.getRatingDataSize());
        channel.position(channel.position() + header.getRatingDataSize());

        ByteBuffer tableBuffer = channel.map(FileChannel.MapMode.READ_ONLY, channel.position(),
                channel.size() - channel.position());
        BinaryIndexTable utbl = BinaryIndexTable.fromBuffer(header.getUserCount(), tableBuffer);
        BinaryIndexTable itbl = BinaryIndexTable.fromBuffer(header.getItemCount(), tableBuffer);

        return new BinaryRatingDAO(file, header, data, utbl, itbl);
    } finally {
        input.close();
    }
}

From source file:org.uva.itast.blended.omr.OMRUtils.java

/**
 * Mtodo que a partir de un fichero pdf de entrada devuelve el
 * nmero su pginas//from  w  w w .  j  av  a 2s .c om
 * 
 * @param inputdir
 * @return pdffile.getNumpages();
 * @throws IOException
 */
public static int getNumpagesPDF(String inputdir) throws IOException {
    RandomAccessFile raf = new RandomAccessFile(inputdir, "r"); // se carga
    // la imagen
    // pdf para
    // leerla
    FileChannel channel = raf.getChannel();
    ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
    PDFFile pdffile = new PDFFile(buf); // se crea un objeto de tipo PDFFile
    // para almacenar las pginas
    return pdffile.getNumPages(); // se obtiene el nmero de paginas
}

From source file:org.mitre.math.linear.BufferRealMatrix.java

/**
 * Attempts to load in a previously saved matrix from the given {@link FileChannel}
 *
 * @param fileChannel// w  ww  . j a  v  a 2  s .  c  o  m
 * @return
 * @throws IOException
 */
public static BufferRealMatrix loadMatrix(FileChannel fileChannel) throws IOException {
    MappedByteBuffer bb = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, BUFFER_HEADER_SIZE);
    bb.clear();

    int block_size = bb.getInt();
    assert (block_size == BLOCK_BYTE_SIZE);

    int rows = bb.getInt();
    int columns = bb.getInt();
    LOG.debug(String.format("Found matrix of %dx%d with %d block sizes", rows, columns, block_size));
    return new BufferRealMatrix(fileChannel, rows, columns);
}