Example usage for java.nio.channels ReadableByteChannel read

List of usage examples for java.nio.channels ReadableByteChannel read

Introduction

In this page you can find the example usage for java.nio.channels ReadableByteChannel read.

Prototype

public int read(ByteBuffer dst) throws IOException;

Source Link

Document

Reads a sequence of bytes from this channel into the given buffer.

Usage

From source file:byps.BWire.java

/**
 * Reads a ByteBuffer from an InputStream
 * Closes the InputStream./*from   w  ww .j  av a 2s.  c  o  m*/
 * @param is
 * @return
 * @throws IOException
 */
public static ByteBuffer bufferFromStream(InputStream is, Boolean gzip) throws IOException {
    if (is == null)
        return null;
    try {
        ByteBuffer ibuf = ByteBuffer.allocate(10 * 1000);

        if (gzip != null) {
            if (gzip) {
                is = new GZIPInputStream(is);
            }
        } else {
            if (!is.markSupported())
                is = new BufferedInputStream(is, 2);
            is.mark(2);
            int magic = is.read() | (is.read() << 8);
            is.reset();
            if (magic == GZIPInputStream.GZIP_MAGIC) {
                is = new GZIPInputStream(is);
            }
        }

        ReadableByteChannel rch = Channels.newChannel(is);
        while (rch.read(ibuf) != -1) {
            if (ibuf.remaining() == 0) {
                ByteBuffer nbuf = ByteBuffer.allocate(ibuf.capacity() * 2);
                ibuf.flip();
                nbuf.put(ibuf);
                ibuf = nbuf;
            }
        }

        ibuf.flip();
        return ibuf;
    } finally {
        is.close();
    }
}

From source file:StreamUtil.java

/**
 * Copies the content read from InputStream to OutputStream. Uses the NIO Channels to copy.
 * @param is The InputStream that is read.
 * @param os The OutputStream where the data is written.
 * @throws IOException//  w  ww  .j a va 2s . co m
 */
public static void copy(final InputStream is, final OutputStream os) throws IOException {
    final ReadableByteChannel inChannel = Channels.newChannel(is);
    final WritableByteChannel outChannel = Channels.newChannel(os);

    try {
        final ByteBuffer buffer = ByteBuffer.allocate(65536);
        while (true) {
            int bytesRead = inChannel.read(buffer);
            if (bytesRead == -1)
                break;
            buffer.flip();
            while (buffer.hasRemaining())
                outChannel.write(buffer);
            buffer.clear();
        }
    } finally {
        try {
            inChannel.close();
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, null, ex);
        }
        try {
            outChannel.close();
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.atilika.kuromoji.trie.DoubleArrayTrie.java

/**
 * Load Stored data/*w  w  w .j  a v a  2  s .c  o  m*/
 *
 * @param input  input stream to read the double array trie from
 * @return double array trie, not null
 * @throws IOException if an IO error occured during reading the double array trie
 */
public static DoubleArrayTrie read(InputStream input) throws IOException {
    DoubleArrayTrie trie = new DoubleArrayTrie();
    DataInputStream dis = new DataInputStream(new BufferedInputStream(input));

    trie.compact = dis.readBoolean();
    int baseCheckSize = dis.readInt(); // Read size of baseArr and checkArr
    int tailSize = dis.readInt(); // Read size of tailArr
    ReadableByteChannel channel = Channels.newChannel(dis);

    ByteBuffer tmpBaseBuffer = ByteBuffer.allocate(baseCheckSize * 4);
    channel.read(tmpBaseBuffer);
    tmpBaseBuffer.rewind();
    trie.baseBuffer = tmpBaseBuffer.asIntBuffer();

    ByteBuffer tmpCheckBuffer = ByteBuffer.allocate(baseCheckSize * 4);
    channel.read(tmpCheckBuffer);
    tmpCheckBuffer.rewind();
    trie.checkBuffer = tmpCheckBuffer.asIntBuffer();

    ByteBuffer tmpTailBuffer = ByteBuffer.allocate(tailSize * 2);
    channel.read(tmpTailBuffer);
    tmpTailBuffer.rewind();
    trie.tailBuffer = tmpTailBuffer.asCharBuffer();

    input.close();
    return trie;
}

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

/**
 * Copies the content from one channel to another.
 *
 * @param srcChannel/* www.  ja v  a2s  .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:com.discovery.darchrow.io.IOWriteUtil.java

/**
 * NIO API ?? ()./*from  w w  w.  j  a v  a2 s  . c  o  m*/
 *
 * @param bufferLength
 *            the buffer length
 * @param inputStream
 *            the input stream
 * @param outputStream
 *            the output stream
 * @since 1.0.8
 * @since jdk1.4
 */
private static void writeUseNIO(int bufferLength, InputStream inputStream, OutputStream outputStream) {
    int i = 0;
    int sumSize = 0;
    int j = 0;

    ///2 
    //As creme de la creme with regard to performance, you could use NIO Channels and ByteBuffer. 

    ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream);
    WritableByteChannel writableByteChannel = Channels.newChannel(outputStream);

    ByteBuffer byteBuffer = ByteBuffer.allocate(bufferLength);

    try {
        while (readableByteChannel.read(byteBuffer) != -1) {
            byteBuffer.flip();
            j = writableByteChannel.write(byteBuffer);
            sumSize += j;
            byteBuffer.clear();
            i++;
        }

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Write data over,sumSize:[{}],bufferLength:[{}],loopCount:[{}]",
                    FileUtil.formatSize(sumSize), bufferLength, i);
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } finally {
        IOUtils.closeQuietly(outputStream);
        IOUtils.closeQuietly(writableByteChannel);
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(readableByteChannel);
    }
}

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

/**
 * Copy data from source to destination nio channel
 *
 * @param source      source channel// w w  w  . ja v  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: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();/*from  ww  w.  j  a  va  2 s .  co 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:cn.tc.ulife.platform.msg.http.util.HttpUtil.java

/**
 * ??// ww w.ja v a 2s.c  o  m
 *
 * @param is
 * @return
 * @throws IOException
 */
public static String readStreamAsStr(InputStream is) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    WritableByteChannel dest = Channels.newChannel(bos);
    ReadableByteChannel src = Channels.newChannel(is);
    ByteBuffer bb = ByteBuffer.allocate(4096);

    while (src.read(bb) != -1) {
        bb.flip();
        dest.write(bb);
        bb.clear();
    }
    src.close();
    dest.close();

    return new String(bos.toByteArray(), Constants.ENCODING);
}

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 . c  o 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:de.metalcon.imageServer.protocol.CreateRequestTest.java

/**
 * compare two input streams// w  w  w.j  a  v  a2 s  .  com
 * 
 * @param stream1
 *            first input stream
 * @param stream2
 *            second input stream
 * @return true - if the two streams does contain the same content<br>
 *         false - otherwise
 * @throws IOException
 *             if IO errors occurred
 */
private static boolean compareInputStreams(final InputStream stream1, final InputStream stream2)
        throws IOException {
    final ReadableByteChannel channel1 = Channels.newChannel(stream1);
    final ReadableByteChannel channel2 = Channels.newChannel(stream2);
    final ByteBuffer buffer1 = ByteBuffer.allocateDirect(4096);
    final ByteBuffer buffer2 = ByteBuffer.allocateDirect(4096);

    try {
        while (true) {

            int n1 = channel1.read(buffer1);
            int n2 = channel2.read(buffer2);

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

            buffer1.flip();
            buffer2.flip();

            for (int i = 0; i < Math.min(n1, n2); i++) {
                if (buffer1.get() != buffer2.get()) {
                    return false;
                }
            }

            buffer1.compact();
            buffer2.compact();
        }

    } finally {
        if (stream1 != null) {
            stream1.close();
        }
        if (stream2 != null) {
            stream2.close();
        }
    }
}