read File from URL to ByteBuffer - Java java.nio

Java examples for java.nio:ByteBuffer Read

Description

read File from URL to ByteBuffer

Demo Code


import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;

public class Main{
    private static final int BLOCK_SIZE = 65536;
    public static ByteBuffer readFile(URL projectUrl) throws IOException {
        ByteBuffer buf = null;//from  ww w  . ja  v a  2  s . com
        BufferedInputStream is = null;
        try {
            is = new BufferedInputStream(projectUrl.openStream());
            // Allocate off-heap
            buf = ByteBuffer.allocateDirect(is.available());
            buf.order(ByteOrder.LITTLE_ENDIAN);
            BinaryUtil.transferToBuf(buf, is);
        } finally {
            if (is != null)
                is.close();
        }
        return buf;
    }
    public static void transferToBuf(ByteBuffer buf, InputStream is)
            throws IOException {
        byte b[] = new byte[BLOCK_SIZE];
        while (is.available() > 0) {
            if (is.available() >= BLOCK_SIZE) {
                is.read(b);
                buf.put(b);
            } else {
                int len = is.available();
                is.read(b);
                buf.put(b, 0, len);
            }
        }
        buf.rewind();
    }
}

Related Tutorials