Example usage for java.nio ByteBuffer compact

List of usage examples for java.nio ByteBuffer compact

Introduction

In this page you can find the example usage for java.nio ByteBuffer compact.

Prototype

public abstract ByteBuffer compact();

Source Link

Document

Compacts this byte buffer.

Usage

From source file:com.mgmtp.perfload.perfalyzer.util.IoUtilities.java

public static void writeToChannel(final WritableByteChannel destChannel, final ByteBuffer buffer) {
    try {/*from   w  w  w . j  a  va 2 s .  c  o  m*/
        // write to the destination channel
        destChannel.write(buffer);

        // If partial transfer, shift remainder down so it does not get lost
        // If buffer is empty, this is the same as calling clear()
        buffer.compact();

        // EOF will leave buffer in fill state
        buffer.flip();

        // make sure the buffer is fully drained
        while (buffer.hasRemaining()) {
            destChannel.write(buffer);
        }
    } catch (IOException ex) {
        throw new UncheckedIOException(ex);
    }
}

From source file:com.meltmedia.cadmium.core.FileSystemManager.java

public static void streamCopy(InputStream streamIn, OutputStream streamOut, boolean leaveOutputOpen)
        throws IOException {
    ReadableByteChannel input = Channels.newChannel(streamIn);
    WritableByteChannel output = Channels.newChannel(streamOut);

    ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);

    while (input.read(buffer) != -1) {
        buffer.flip();//from   w  ww.j a  v a 2  s  .  co m

        output.write(buffer);

        buffer.compact();
    }

    buffer.flip();

    // Make sure the buffer is empty
    while (buffer.hasRemaining()) {
        output.write(buffer);
    }

    input.close();
    if (!leaveOutputOpen) {
        output.close();
    }
}

From source file:com.mymed.android.myjam.controller.HttpCall.java

/**
 * Given an InputStream reads the bytes as UTF8 chars and return a 
 * String.//from w w w  .  j a v  a2s  .  c o  m
 * @param is Input stream.
 * @param length Length of the stream in bytes.
 * @return The string
 * @throws InternalBackEndException Format is not correct or the length less then the real wrong.
 */
private static String convertStreamToString(InputStream is, long length) throws InternalClientException {
    String streamString;
    if (length > Integer.MAX_VALUE)
        throw new InternalClientException("Wrong Content");
    int byteLength = (int) length;
    try {
        if (byteLength > 0) {
            ByteBuffer byteBuff = ByteBuffer.allocate(byteLength);
            int currByte;
            while ((currByte = is.read()) != -1) {
                byteBuff.put((byte) currByte);
            }
            byteBuff.compact();
            final CharBuffer charBuf = CHARSET.newDecoder().decode(byteBuff);
            streamString = charBuf.toString();
            return streamString;
        } else {
            BufferedReader buffRead = new BufferedReader(
                    new InputStreamReader(is, Charset.forName(CHARSET_NAME)));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = buffRead.readLine()) != null) {
                sb.append(line + "\n");
            }
            return sb.toString();
        }
    } catch (IOException e) {
        throw new InternalClientException("Wrong content");
    } catch (BufferOverflowException e) {
        throw new InternalClientException("Wrong length");
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.glaf.core.util.ByteBufferUtils.java

public static boolean compact(ByteBuffer buffer) {
    if (buffer.position() == 0) {
        return false;
    }//from  w ww  . ja  v a  2  s.c  o  m
    boolean full = buffer.limit() == buffer.capacity();
    buffer.compact().flip();
    return full && buffer.limit() < buffer.capacity();
}

From source file:com.pavlospt.rxfile.RxFile.java

private static void fastChannelCopy(final ReadableByteChannel src, final WritableByteChannel dest)
        throws IOException {
    final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
    while (src.read(buffer) != -1) {
        buffer.flip();//from w w  w.  ja  v a2s. com
        dest.write(buffer);
        buffer.compact();
    }
    buffer.flip();
    while (buffer.hasRemaining()) {
        dest.write(buffer);
    }
}

From source file:com.flexive.shared.FxFileUtils.java

/**
 * Copy data from source to destination nio channel
 *
 * @param source      source channel//from w  w  w.  j  av  a  2 s .c  om
 * @param destination destination channel
 * @return total number of bytes copied
 * @throws java.io.IOException on errors
 */
public static long copyNIOChannel(ReadableByteChannel source, WritableByteChannel destination)
        throws IOException {
    ByteBuffer xferBuffer = ByteBuffer.allocateDirect(4096);
    long count = 0, read, written;
    while (true) {
        read = source.read(xferBuffer);
        if (read < 0)
            return count;
        xferBuffer.flip();
        written = destination.write(xferBuffer);
        if (written > 0) {
            count += written;
            if (xferBuffer.hasRemaining())
                xferBuffer.compact();
            else
                xferBuffer.clear();
        } else {
            while (xferBuffer.hasRemaining()) {
                try {
                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    LOG.warn(e);
                }
                written = destination.write(xferBuffer);
                if (written > 0) {
                    count += written;
                    if (xferBuffer.hasRemaining())
                        xferBuffer.compact();
                }
            }
            if (!xferBuffer.hasRemaining())
                xferBuffer.clear();
        }
    }
}

From source file:com.mgmtp.perfload.perfalyzer.util.IoUtilities.java

/**
 * Copies the content from one channel to another.
 *
 * @param srcChannel/*from   w w w  .  ja  v  a  2  s.c o  m*/
 *       the source channel to copy from
 * @param destChannel
 *       the destination channel to copy to
 */
public static void copy(final ReadableByteChannel srcChannel, final WritableByteChannel destChannel)
        throws IOException {
    final ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER_SIZE);
    while (srcChannel.read(buffer) != -1) {
        // flip the buffer so it can be written to the destination channel
        buffer.flip();

        // write to the destination channel
        destChannel.write(buffer);

        // If partial transfer, shift remainder down so it does not get lost
        // If buffer is empty, this is the same as calling clear()
        buffer.compact();
    }

    // EOF will leave buffer in fill state
    buffer.flip();

    // make sure the buffer is fully drained
    while (buffer.hasRemaining()) {
        destChannel.write(buffer);
    }
}

From source file:schemacrawler.test.utility.TestUtility.java

private static void fastChannelCopy(final ReadableByteChannel src, final WritableByteChannel dest)
        throws IOException {
    final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
    while (src.read(buffer) != -1) {
        // prepare the buffer to be drained
        buffer.flip();/*  www .  j  a  va2s  .c o m*/
        // write to the channel, may block
        dest.write(buffer);
        // If partial transfer, shift remainder down
        // If buffer is empty, same as doing clear()
        buffer.compact();
    }
    // EOF will leave buffer in fill state
    buffer.flip();
    // make sure the buffer is fully drained.
    while (buffer.hasRemaining()) {
        dest.write(buffer);
    }
}

From source file:org.dawnsci.dde.templates.AbstractTemplateTestBase.java

private static boolean isEqual(InputStream i1, InputStream i2) throws IOException {

    ReadableByteChannel ch1 = Channels.newChannel(i1);
    ReadableByteChannel ch2 = Channels.newChannel(i2);

    ByteBuffer buf1 = ByteBuffer.allocateDirect(1024);
    ByteBuffer buf2 = ByteBuffer.allocateDirect(1024);

    try {//from  w ww .  j av a  2  s. co m
        while (true) {

            int n1 = ch1.read(buf1);
            int n2 = ch2.read(buf2);

            if (n1 == -1 || n2 == -1)
                return n1 == n2;

            buf1.flip();
            buf2.flip();

            for (int i = 0; i < Math.min(n1, n2); i++)
                if (buf1.get() != buf2.get())
                    return false;

            buf1.compact();
            buf2.compact();
        }

    } finally {
        if (i1 != null)
            i1.close();
        if (i2 != null)
            i2.close();
    }
}

From source file:Main.java

public static void copy(ReadableByteChannel in, WritableByteChannel out) throws IOException {
    // First, we need a buffer to hold blocks of copied bytes.
    ByteBuffer buffer = ByteBuffer.allocateDirect(32 * 1024);

    // Now loop until no more bytes to read and the buffer is empty
    while (in.read(buffer) != -1 || buffer.position() > 0) {
        // The read() call leaves the buffer in "fill mode". To prepare
        // to write bytes from the bufferwe have to put it in "drain mode"
        // by flipping it: setting limit to position and position to zero
        buffer.flip();//from w  w  w . j ava  2  s . c o  m

        // Now write some or all of the bytes out to the output channel
        out.write(buffer);

        // Compact the buffer by discarding bytes that were written,
        // and shifting any remaining bytes. This method also
        // prepares the buffer for the next call to read() by setting the
        // position to the limit and the limit to the buffer capacity.
        buffer.compact();
    }
}