Example usage for java.nio ByteBuffer hasRemaining

List of usage examples for java.nio ByteBuffer hasRemaining

Introduction

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

Prototype

public final boolean hasRemaining() 

Source Link

Document

Indicates if there are elements remaining in this buffer, that is if position < limit .

Usage

From source file:Main.java

public 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();//w  w w .ja  v  a 2s  . 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 recycle()
        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:io.blobkeeper.file.util.FileUtils.java

public static ByteBuffer readFile(@NotNull File file, long offset, long length) {
    ByteBuffer byteBuffer = ByteBuffer.allocate((int) length);
    int bytesRead = 0;
    try {/*  w w  w.  j  ava 2  s.  co  m*/
        // TODO: for exclusively read of file channel by single thread we can use read w/o offset (avoid additional seeks?)
        while ((bytesRead = file.getFileChannel().read(byteBuffer, offset)) != -1) {
            if (!byteBuffer.hasRemaining()) {
                byteBuffer.flip();
                return byteBuffer;
            }
            offset += bytesRead;
        }
    } catch (Exception e) {
        log.error("Can't read file", e);
    }

    if (bytesRead < byteBuffer.capacity()) {
        String error = String.format("File read error for file %s", file);
        log.error(error);
        throw new IllegalArgumentException(error);
    }

    byteBuffer.flip();
    return byteBuffer;
}

From source file:com.mcxiaoke.next.http.util.URLUtils.java

private static String urlEncode(final String content, final Charset charset, final BitSet safechars,
        final boolean blankAsPlus) {
    if (content == null) {
        return null;
    }/* www .  j a v  a2s .  c  om*/
    final StringBuilder buf = new StringBuilder();
    final ByteBuffer bb = charset.encode(content);
    while (bb.hasRemaining()) {
        final int b = bb.get() & 0xff;
        if (safechars.get(b)) {
            buf.append((char) b);
        } else if (blankAsPlus && b == ' ') {
            buf.append('+');
        } else {
            buf.append("%");
            final char hex1 = Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, RADIX));
            final char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, RADIX));
            buf.append(hex1);
            buf.append(hex2);
        }
    }
    return buf.toString();
}

From source file:org.lealone.cluster.utils.ByteBufferUtil.java

public static InputStream inputStream(ByteBuffer bytes) {
    final ByteBuffer copy = bytes.duplicate();

    return new InputStream() {
        @Override/*w  w  w  .  ja  v  a2s .  c  o m*/
        public int read() {
            if (!copy.hasRemaining())
                return -1;

            return copy.get() & 0xFF;
        }

        @Override
        public int read(byte[] bytes, int off, int len) {
            if (!copy.hasRemaining())
                return -1;

            len = Math.min(len, copy.remaining());
            copy.get(bytes, off, len);
            return len;
        }

        @Override
        public int available() {
            return copy.remaining();
        }
    };
}

From source file:yui.classes.utils.IOUtils.java

public static byte[] fileReadNIO(String name) {
    FileInputStream f = null;//w ww .j a  v a  2  s.co m
    ByteBuffer bb = null;
    try {
        f = new FileInputStream(name);

        FileChannel ch = f.getChannel();
        bb = ByteBuffer.allocateDirect(1024);

        long checkSum = 0L;
        int nRead;
        while ((nRead = ch.read(bb)) != -1) {
            bb.position(0);
            bb.limit(nRead);
            while (bb.hasRemaining()) {
                checkSum += bb.get();
            }
            bb.clear();
        }
    } catch (FileNotFoundException ex) {
        logger.error(ex.getMessage());
    } catch (IOException ex) {
        logger.error(ex.getMessage());
    } finally {
        try {
            f.close();
        } catch (IOException ex) {
            logger.error(ex.getMessage());
        }
    }
    return bb.array();

}

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

public static void readFrom(InputStream is, int needed, ByteBuffer buffer) throws IOException {
    ByteBuffer tmp = allocate(8192);
    while (needed > 0 && buffer.hasRemaining()) {
        int l = is.read(tmp.array(), 0, 8192);
        if (l < 0) {
            break;
        }/*ww w . j  a v  a2s. c  o m*/
        tmp.position(0);
        tmp.limit(l);
        buffer.put(tmp);
    }
}

From source file:it.geosolutions.tools.io.file.IOUtils.java

/**
 * Copies the content of the source channel onto the destination channel.
 * //from   www.  j  a va2  s  .c  om
 * @param bufferSize
 *            size of the temp buffer to use for this copy.
 * @param source
 *            the source {@link ReadableByteChannel}.
 * @param destination
 *            the destination {@link WritableByteChannel};.
 * @throws IOException
 *             in case something bad happens.
 */
public static void copyChannel(int bufferSize, ReadableByteChannel source, WritableByteChannel destination)
        throws IOException {

    Objects.notNull(source, destination);
    if (!source.isOpen() || !destination.isOpen())
        throw new IllegalStateException("Source and destination channels must be open.");

    final java.nio.ByteBuffer buffer = java.nio.ByteBuffer.allocateDirect(bufferSize);
    while (source.read(buffer) != -1) {
        // prepare the buffer for draining
        buffer.flip();

        // write to destination
        while (buffer.hasRemaining())
            destination.write(buffer);

        // clear
        buffer.clear();

    }

}

From source file:org.gcaldaemon.core.ldap.LDAPListener.java

private static final void processWrite(SelectionKey key) throws Exception {
    Object att = key.attachment();
    if (att == null) {
        Thread.sleep(100);/*from  w w w. j  a va2 s. c  o m*/
        return;
    }
    if (att instanceof ByteBuffer) {
        ByteBuffer buffer = (ByteBuffer) att;
        if (!buffer.hasRemaining()) {
            key.attach(new byte[0]);
            key.interestOps(SelectionKey.OP_READ);
            return;
        }
        SocketChannel channel = (SocketChannel) key.channel();
        channel.write(buffer);
    }
}

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  w w  .  j  a  va 2s  . 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.msr.dnsdemo.network.DownloadFile.java

public static void fastChannelCopy(final ReadableByteChannel src, final WritableByteChannel dest)
        throws IOException, NullPointerException {
    if (src != null && dest != null) {
        final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
        while (src.read(buffer) != -1) {
            // prepare the buffer to be drained
            buffer.flip();/*from w  w  w  . j a  v  a2 s.c  om*/
            // 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);
        }
    }
}