Example usage for java.nio ByteBuffer flip

List of usage examples for java.nio ByteBuffer flip

Introduction

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

Prototype

public final Buffer flip() 

Source Link

Document

Flips this buffer.

Usage

From source file:com.google.cloud.public_datasets.nexrad2.GcsUntar.java

private static File downloadFromGcs(String bucketName, String blobName, File tmpDir) throws IOException {
    Storage storage = StorageOptions.getDefaultInstance().getService();
    File fileName = File.createTempFile("download", "bytes", tmpDir);
    try (ReadChannel reader = storage.reader(bucketName, blobName);
            FileOutputStream writer = new FileOutputStream(fileName)) {
        ByteBuffer bytes = ByteBuffer.allocate(64 * 1024);
        while (reader.read(bytes) > 0) {
            bytes.flip();
            writer.getChannel().write(bytes);
            bytes.clear();//from   www. ja  v a 2  s. c om
        }
    }
    return fileName;
}

From source file:com.liveramp.commons.util.BytesUtils.java

public static ByteBuffer byteBufferDeepCopy(ByteBuffer src) {
    ByteBuffer copy = ByteBuffer.allocate(src.remaining()).put(src.slice());
    copy.flip();
    return copy;/*from   w  w w  .  j  a  va 2  s  .  c  o  m*/
}

From source file:Main.java

public static String byteBufferToString(ByteBuffer buffer) {
    CharBuffer charBuffer = null;
    try {/*from  w  w w .  j a va2  s  . co  m*/
        Charset charset = Charset.forName("UTF-8");
        CharsetDecoder decoder = charset.newDecoder();
        charBuffer = decoder.decode(buffer);
        buffer.flip();
        return charBuffer.toString();
    } catch (Exception ex) {
        ex.printStackTrace();
        return "";
    }
}

From source file:com.alibaba.otter.shared.common.utils.NioUtilsPerformance.java

public static void channelTest(File source, File target) throws Exception {
    FileInputStream fis = null;/*from w  w w.  j a  va 2  s . com*/
    FileOutputStream fos = null;
    try {
        fis = new FileInputStream(source);
        fos = new FileOutputStream(target);
        FileChannel sChannel = fis.getChannel();
        FileChannel tChannel = fos.getChannel();

        target.createNewFile();

        ByteBuffer buffer = ByteBuffer.allocate(16 * 1024);
        while (sChannel.read(buffer) > 0) {
            buffer.flip();
            tChannel.write(buffer);
            buffer.clear();
        }

        tChannel.close();
        sChannel.close();
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(fos);
    }
}

From source file:com.oneguy.recognize.Util.java

public static ByteBuffer doubleSize(ByteBuffer buffer) {
    if (buffer == null) {
        return null;
    }//from   w  ww  .ja va2  s.co m
    byte[] content = new byte[buffer.position()];
    buffer.flip();
    buffer.get(content);
    ByteBuffer newBuffer = ByteBuffer.allocate(buffer.capacity() * 2);
    newBuffer.put(content);
    return newBuffer;
}

From source file:ChannelToWriter.java

/**
 * Read bytes from the specified channel, decode them using the specified
 * Charset, and write the resulting characters to the specified writer
 *///from w  w w.j a va 2  s.c om
public static void copy(ReadableByteChannel channel, Writer writer, Charset charset) throws IOException {
    // Get and configure the CharsetDecoder we'll use
    CharsetDecoder decoder = charset.newDecoder();
    decoder.onMalformedInput(CodingErrorAction.IGNORE);
    decoder.onUnmappableCharacter(CodingErrorAction.IGNORE);

    // Get the buffers we'll use, and the backing array for the CharBuffer.
    ByteBuffer bytes = ByteBuffer.allocateDirect(2 * 1024);
    CharBuffer chars = CharBuffer.allocate(2 * 1024);
    char[] array = chars.array();

    while (channel.read(bytes) != -1) { // Read from channel until EOF
        bytes.flip(); // Switch to drain mode for decoding
        // Decode the byte buffer into the char buffer.
        // Pass false to indicate that we're not done.
        decoder.decode(bytes, chars, false);

        // Put the char buffer into drain mode, and write its contents
        // to the Writer, reading them from the backing array.
        chars.flip();
        writer.write(array, chars.position(), chars.remaining());

        // Discard all bytes we decoded, and put the byte buffer back into
        // fill mode. Since all characters were output, clear that buffer.
        bytes.compact(); // Discard decoded bytes
        chars.clear(); // Clear the character buffer
    }

    // At this point there may still be some bytes in the buffer to decode
    // So put the buffer into drain mode call decode() a final time, and
    // finish with a flush().
    bytes.flip();
    decoder.decode(bytes, chars, true); // True means final call
    decoder.flush(chars); // Flush any buffered chars
    // Write these final chars (if any) to the writer.
    chars.flip();
    writer.write(array, chars.position(), chars.remaining());
    writer.flush();
}

From source file:Main.java

private static ByteBuffer allocateMore(ByteBuffer output) {
    if (output.capacity() == 0) {
        return ByteBuffer.allocate(1);
    }//from   w  ww.ja v  a  2 s  . co  m
    ByteBuffer result = ByteBuffer.allocate(output.capacity() * 2);
    output.flip();
    result.put(output);
    return result;
}

From source file:com.offbynull.portmapper.common.ByteBufferUtils.java

/**
 * Copy the remaining content of a {@link ByteBuffer} in to a new non-direct {@link ByteBuffer}.
 * @param src buffer to copy//w ww . ja  v a  2 s  .  c  o m
 * @param incrementSrc of {@code true} increments {@code src}'s position
 * @param incrementDst of {@code true} increments {@code dst}'s position
 * @return new buffer with the remaining content in {@code src}
 * @throws NullPointerException if any arguments are {@code null}
 */
public static ByteBuffer copyContents(ByteBuffer src, boolean incrementSrc, boolean incrementDst) {
    Validate.notNull(src);
    if (!incrementSrc) {
        src.mark();
    }

    ByteBuffer dst = ByteBuffer.allocate(src.remaining());
    dst.put(src);

    if (!incrementSrc) {
        src.reset();
    }

    if (!incrementDst) {
        dst.flip();
    }

    return dst;
}

From source file:com.buaa.cfs.common.oncrpc.XDR.java

/** Write an XDR message to a TCP ChannelBuffer */
public static ChannelBuffer writeMessageTcp(XDR request, boolean last) {
    Preconditions.checkState(request.state == XDR.State.WRITING);
    ByteBuffer b = request.buf.duplicate();
    b.flip();
    byte[] fragmentHeader = XDR.recordMark(b.limit(), last);
    ByteBuffer headerBuf = ByteBuffer.wrap(fragmentHeader);

    // TODO: Investigate whether making a copy of the buffer is necessary.
    return ChannelBuffers.copiedBuffer(headerBuf, b);
}

From source file:org.hawk.service.api.utils.APIUtils.java

public static File convertJavaFileToThriftFile(java.io.File rawFile) throws FileNotFoundException, IOException {
    try (FileInputStream fIS = new FileInputStream(rawFile)) {
        FileChannel chan = fIS.getChannel();

        /* Note: this cast limits us to 2GB files - this shouldn't
         be a problem, but if it were we could use FileChannel#map
         and call Hawk.Client#registerModels one file at a time. */
        ByteBuffer buf = ByteBuffer.allocate((int) chan.size());
        chan.read(buf);//from  w ww .j  a v  a2 s.c o m
        buf.flip();

        File mmFile = new File();
        mmFile.name = rawFile.getName();
        mmFile.contents = buf;
        return mmFile;
    }
}