Java ByteBuffer Put inputStreamToByteBuffer(InputStream input)

Here you can find the source of inputStreamToByteBuffer(InputStream input)

Description

Loads an input stream fully keeping the whole file in memory.

License

Open Source License

Parameter

Parameter Description
input will be read and closed

Return

data read

Declaration

public static ByteBuffer inputStreamToByteBuffer(InputStream input) throws IOException 

Method Source Code


//package com.java2s;
/*//from  w w  w.j  av  a 2s. c o  m
 * Copyright (C) 2010 Stephen Tigner
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
 * 02111-1307, USA.
 */

import java.io.*;
import java.nio.ByteBuffer;

public class Main {
    /**
     * Loads an input stream fully <b>keeping the whole file in memory</b>.
     * <b>WARNING</b>This method should be avoided on Android and other memory constrained devices, unless you are discarding the returned ByteBuffer
     *
     * @param input will be read and closed
     * @return data read
     */
    public static ByteBuffer inputStreamToByteBuffer(InputStream input) throws IOException {
        ByteArrayOutputStream bas = new ByteArrayOutputStream(1000000); // 1MB is a waste, but this method should be avoided on memory-constrained devices anyway
        byte[] buf = new byte[1024];
        int n;
        while ((n = input.read(buf)) != -1)
            bas.write(buf, 0, n);
        input.close();
        buf = bas.toByteArray();
        ByteBuffer byteBuffer = ByteBuffer.wrap(buf);
        return byteBuffer;
    }

    /** Close if possible */
    public static void close(Appendable output) throws IOException {
        if (output instanceof Closeable)
            ((Closeable) output).close();
    }
}

Related

  1. deserializeString(ByteBuffer inputBuffer, Charset charset)
  2. extractString(ByteArrayOutputStream byteBuffer)
  3. flushOutputStreamWriter(OutputStream out, ByteBuffer bytes, CharsetEncoder encoder, Object lock)
  4. getZeroTerminatedStringBytesArray( ByteBuffer inputBuffer)
  5. inputStream(ByteBuffer bytes)
  6. inputStreamToByteBuffer(InputStream is)
  7. makeInputStream(final ByteBuffer buffer)
  8. moveBufferToStream(OutputStream out, ByteBuffer in, int length)
  9. outputBuffer(ByteBuffer buffer)