Read File to ByteBuffer - Java java.nio

Java examples for java.nio:ByteBuffer Read

Description

Read File to ByteBuffer

Demo Code

/*//  ww w.j a  v a2  s . c o m
 * Copyright (c) 2015. Philip DeCamp
 * Released under the BSD 2-Clause License
 * http://opensource.org/licenses/BSD-2-Clause
 */
//package com.java2s;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
    public static ByteBuffer bufferFile(File file) throws IOException {
        long size = file.length();

        ByteBuffer buf = ByteBuffer.allocate((int) (size & 0x7FFFFFFF));
        FileChannel chan = new FileInputStream(file).getChannel();
        while (buf.remaining() > 0) {
            int n = chan.read(buf);
            if (n <= 0)
                throw new IOException("Read operation failed.");
        }

        chan.close();
        buf.flip();
        return buf;
    }
}

Related Tutorials