Java ByteBuffer Put byteBufferToOutputStream(ByteBuffer in, OutputStream out)

Here you can find the source of byteBufferToOutputStream(ByteBuffer in, OutputStream out)

Description

Reads the full contents of a ByteBuffer and writes them to an OutputStream.

License

Apache License

Parameter

Parameter Description
in ByteBuffer to write into the OutputStream
out Destination stream

Exception

Parameter Description
IOException If there is an error writing into the OutputStream

Declaration

public static void byteBufferToOutputStream(ByteBuffer in, OutputStream out) throws IOException 

Method Source Code


//package com.java2s;
/*/*from  www . j  a v a 2s.c o  m*/
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.IOException;

import java.io.OutputStream;
import java.nio.ByteBuffer;

public class Main {
    /**
     * Reads the full contents of a ByteBuffer and writes them to an OutputStream. The ByteBuffer is
     * consumed by this operation; eg in.remaining() will be 0 after it completes successfully.
     * @param in  ByteBuffer to write into the OutputStream
     * @param out Destination stream
     * @throws IOException If there is an error writing into the OutputStream
     */
    public static void byteBufferToOutputStream(ByteBuffer in, OutputStream out) throws IOException {
        final int BUF_SIZE = 8192;

        if (in.hasArray()) {
            out.write(in.array(), in.arrayOffset() + in.position(), in.remaining());
        } else {
            final byte[] b = new byte[Math.min(in.remaining(), BUF_SIZE)];
            while (in.remaining() > 0) {
                int bytesToRead = Math.min(in.remaining(), BUF_SIZE);
                in.get(b, 0, bytesToRead);

                out.write(b, 0, bytesToRead);
            }
        }
    }
}

Related

  1. bufToStream(ByteBuffer b, OutputStream out)
  2. byteBufferToInputStream(final ByteBuffer byteBuffer)
  3. checkReadSpace(FileInputStream aStream, ByteBuffer aBuf)
  4. computeSize(ByteBuffer[] buffers)
  5. convert(Object lock, CharsetEncoder encoder, ByteBuffer bytes, CharBuffer chars, OutputStream out)
  6. deserializeString(ByteBuffer inputBuffer, Charset charset)