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:ChannelToWriter.java

/**
 * Read bytes from the specified channel, decode them using the specified
 * Charset, and write the resulting characters to the specified writer
 *///from   ww w.ja  va2s .c o  m
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: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 va2  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:org.activiti.engine.test.api.repository.diagram.ProcessDiagramRetrievalTest.java

private static boolean isEqual(InputStream stream1, InputStream stream2) throws IOException {

    ReadableByteChannel channel1 = Channels.newChannel(stream1);
    ReadableByteChannel channel2 = Channels.newChannel(stream2);

    ByteBuffer buffer1 = ByteBuffer.allocateDirect(1024);
    ByteBuffer buffer2 = ByteBuffer.allocateDirect(1024);

    try {//from ww w.  j a v a  2s. c  o  m
        while (true) {

            int bytesReadFromStream1 = channel1.read(buffer1);
            int bytesReadFromStream2 = channel2.read(buffer2);

            if (bytesReadFromStream1 == -1 || bytesReadFromStream2 == -1)
                return bytesReadFromStream1 == bytesReadFromStream2;

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

            for (int i = 0; i < Math.min(bytesReadFromStream1, bytesReadFromStream2); i++)
                if (buffer1.get() != buffer2.get())
                    return false;

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

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

From source file:com.sunchenbin.store.feilong.core.io.IOWriteUtil.java

/**
 * NIO API ?? ().//from   w  w  w .  j  av a2 s.  c om
 * 
 * <h3>NIO</h3>
 * 
 * <blockquote>
 * <p>
 * nionew io,jdk1.4,??<br>
 * nio??<br>
 * </p>
 * 
 * <p>
 * ??,<br>
 * ?,,??? ????cpu,?cpu? <br>
 * ? Java IO ,? IO,NIO ?? IO
 * </p>
 * 
 * <p>
 * The new I/O (NIO) APIs introduced in v 1.4 provide new features and improved performance in the areas of buffer management, scalable
 * network and file I/O, character-set support, and regular-expression matching. The NIO APIs supplement the I/O facilities in the
 * java.io package.
 * </p>
 * 
 * <p>
 * The NIO APIs include the following features:
 * </p>
 * 
 * <ol>
 * <li>Buffers for data of primitive types</li>
 * <li>Character-set encoders and decoders</li>
 * <li>A pattern-matching facility based on Perl-style regular expressions</li>
 * <li>Channels, a new primitive I/O abstraction</li>
 * <li>A file interface that supports locks and memory mapping</li>
 * <li>A multiplexed, non-blocking I/O facility for writing scalable servers</li>
 * </ol>
 * </blockquote>
 * 
 * <p>
 * As creme de la creme with regard to performance,you could use NIO {@link java.nio.channels.Channels} and {@link java.nio.ByteBuffer}.
 * </p>
 *
 * @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) {
    Date beginDate = new Date();
    ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream);
    WritableByteChannel writableByteChannel = Channels.newChannel(outputStream);
    ByteBuffer byteBuffer = ByteBuffer.allocate(bufferLength);

    try {
        int loopCount = 0;
        int sumSize = 0;
        while (readableByteChannel.read(byteBuffer) != -1) {
            byteBuffer.flip();
            sumSize += writableByteChannel.write(byteBuffer);
            byteBuffer.clear();
            loopCount++;
        }
        if (LOGGER.isDebugEnabled()) {
            String formatSize = FileUtil.formatSize(sumSize);
            String time = DateExtensionUtil.getIntervalForView(beginDate, new Date());
            LOGGER.debug("Write data over,sumSize:[{}],bufferLength:[{}],loopCount:[{}],time:{}", formatSize,
                    bufferLength, loopCount, time);
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } finally {
        IOUtils.closeQuietly(outputStream);
        IOUtils.closeQuietly(writableByteChannel);
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(readableByteChannel);
    }
}

From source file:com.feilong.commons.core.io.IOWriteUtil.java

/**
 * NIO API ?? ()./*from   www .j  a  va2s .  com*/
 *
 * @param bufferLength
 *            the buffer length
 * @param inputStream
 *            the input stream
 * @param outputStream
 *            the output stream
 * @throws UncheckedIOException
 *             the unchecked io exception
 * @since 1.0.8
 */
private static void writeUseNIO(int bufferLength, InputStream inputStream, OutputStream outputStream)
        throws UncheckedIOException {
    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 (log.isDebugEnabled()) {
            log.debug("Write data over,sumSize:[{}],bufferLength:[{}],loopCount:[{}]",
                    FileUtil.formatSize(sumSize), bufferLength, i);
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } finally {
        try {
            if (writableByteChannel != null) {
                outputStream.close();
                writableByteChannel.close();
            }
            if (readableByteChannel != null) {
                inputStream.close();
                readableByteChannel.close();
            }
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}

From source file:net.vexelon.myglob.utils.Utils.java

/**
 * Reads an input stream into a byte array
 * @param source/*ww  w .j  av a 2  s  .com*/
 * @return Byte array of input stream data
 * @throws IOException
 */
public static byte[] read(InputStream source) throws IOException {
    ReadableByteChannel srcChannel = Channels.newChannel(source);
    ByteArrayOutputStream baos = new ByteArrayOutputStream(
            source.available() > 0 ? source.available() : BUFFER_PAGE_SIZE);
    WritableByteChannel destination = Channels.newChannel(baos);

    try {
        ByteBuffer buffer = ByteBuffer.allocate(BUFFER_PAGE_SIZE);
        while (srcChannel.read(buffer) > 0) {
            buffer.flip();
            while (buffer.hasRemaining()) {
                destination.write(buffer);
            }
            buffer.clear();
        }
        return baos.toByteArray();
    } catch (IOException e) {
        throw e;
    } finally {
        try {
            if (srcChannel != null)
                srcChannel.close();
        } catch (IOException e) {
        }
        try {
            if (source != null)
                source.close();
        } catch (IOException e) {
        }
        try {
            if (destination != null)
                destination.close();
        } catch (IOException e) {
        }
    }
}

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 .j  a  va  2 s. co  m*/
        dest.write(buffer);
        buffer.compact();
    }
    buffer.flip();
    while (buffer.hasRemaining()) {
        dest.write(buffer);
    }
}

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

public static byte[] getBytes(InputStream inputStream) {
    if (inputStream == null) {
        return null;
    }/*from   w ww  . j  a v a  2s. c  o m*/
    ByteArrayOutputStream output = null;
    try {
        ByteBuffer buffer = ByteBuffer.allocate(8192);
        ReadableByteChannel readChannel = Channels.newChannel(inputStream);
        output = new ByteArrayOutputStream(32 * 1024);
        WritableByteChannel writeChannel = Channels.newChannel(output);
        while ((readChannel.read(buffer)) > 0 || buffer.position() != 0) {
            buffer.flip();
            writeChannel.write(buffer);
            buffer.compact();
        }
        return output.toByteArray();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } finally {
        if (output != null) {
            try {
                output.close();
                output = null;
            } catch (IOException ex) {
            }
        }
    }
}

From source file:net.darkmist.alib.io.BufferUtil.java

/**
 * Allocate a buffer and fill it from a channel. The returned
 * buffer will be rewound to the begining.
 * @return Buffer containing size bytes from the channel.
 * @throws IOException if the channel read does.
 * @throws EOFException if a end of stream is encountered
 *    before the full size is read.//from  w w w . java 2 s  .  co m
 */
public static ByteBuffer allocateAndReadAll(int size, ReadableByteChannel channel) throws IOException {
    ByteBuffer buf = ByteBuffer.allocate(size);
    int justRead;
    int totalRead = 0;

    // FIXME, this will be a tight loop if the channel is non-blocking...
    while (totalRead < size) {
        logger.debug("reading totalRead={}", totalRead);
        if ((justRead = channel.read(buf)) < 0)
            throw new EOFException("Unexpected end of stream after reading " + totalRead + " bytes");
        totalRead += justRead;
    }
    buf.rewind();
    return buf;
}

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

/**
 * Copies the content of the source channel onto the destination channel.
 * /*from ww w .ja v a 2 s. com*/
 * @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();

    }

}