Example usage for java.nio.channels WritableByteChannel close

List of usage examples for java.nio.channels WritableByteChannel close

Introduction

In this page you can find the example usage for java.nio.channels WritableByteChannel close.

Prototype

public void close() throws IOException;

Source Link

Document

Closes this channel.

Usage

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  w  w.  j a v a  2  s  .c om*/
 */
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.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  v a2  s . c o  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:net.vexelon.myglob.utils.Utils.java

/**
 * Reads an input stream into a byte array
 * @param source//from   w  ww  .j a va  2s .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:io.druid.segment.data.VSizeIndexedIntsWriterTest.java

private void checkSerializedSizeAndData() throws Exception {
    int maxValue = vals.length == 0 ? 0 : Ints.max(vals);
    VSizeIndexedIntsWriter writer = new VSizeIndexedIntsWriter(ioPeon, "test", maxValue);

    VSizeIndexedInts intsFromList = VSizeIndexedInts.fromList(Ints.asList(vals), maxValue);
    writer.open();//w  ww .  j av a2  s .c  o  m
    for (int val : vals) {
        writer.add(val);
    }
    writer.close();
    long writtenLength = writer.getSerializedSize();
    final WritableByteChannel outputChannel = Channels.newChannel(ioPeon.makeOutputStream("output"));
    writer.writeToChannel(outputChannel);
    outputChannel.close();

    assertEquals(writtenLength, intsFromList.getSerializedSize());

    // read from ByteBuffer and check values
    VSizeIndexedInts intsFromByteBuffer = VSizeIndexedInts
            .readFromByteBuffer(ByteBuffer.wrap(IOUtils.toByteArray(ioPeon.makeInputStream("output"))));
    assertEquals(vals.length, intsFromByteBuffer.size());
    for (int i = 0; i < vals.length; ++i) {
        assertEquals(vals[i], intsFromByteBuffer.get(i));
    }
}

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

/**
 * NIO API ?? ().//  ww w . j  a  va2 s.c o m
 *
 * @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:io.druid.segment.data.CompressedVSizeIntsIndexedWriterTest.java

private void checkSerializedSizeAndData(int chunkSize) throws Exception {
    CompressedVSizeIntsIndexedWriter writer = new CompressedVSizeIntsIndexedWriter(ioPeon, "test",
            vals.length > 0 ? Ints.max(vals) : 0, chunkSize, byteOrder, compressionStrategy);
    CompressedVSizeIntsIndexedSupplier supplierFromList = CompressedVSizeIntsIndexedSupplier.fromList(
            Ints.asList(vals), vals.length > 0 ? Ints.max(vals) : 0, chunkSize, byteOrder, compressionStrategy);
    writer.open();/*from w  w  w .  j a  v  a2 s.  co m*/
    for (int val : vals) {
        writer.add(val);
    }
    writer.close();
    long writtenLength = writer.getSerializedSize();
    final WritableByteChannel outputChannel = Channels.newChannel(ioPeon.makeOutputStream("output"));
    writer.writeToChannel(outputChannel);
    outputChannel.close();

    assertEquals(writtenLength, supplierFromList.getSerializedSize());

    // read from ByteBuffer and check values
    CompressedVSizeIntsIndexedSupplier supplierFromByteBuffer = CompressedVSizeIntsIndexedSupplier
            .fromByteBuffer(ByteBuffer.wrap(IOUtils.toByteArray(ioPeon.makeInputStream("output"))), byteOrder);
    IndexedInts indexedInts = supplierFromByteBuffer.get();
    for (int i = 0; i < vals.length; ++i) {
        assertEquals(vals[i], indexedInts.get(i));
    }
    CloseQuietly.close(indexedInts);
}

From source file:io.druid.segment.data.CompressedIntsIndexedWriterTest.java

private void checkSerializedSizeAndData(int chunkFactor) throws Exception {
    CompressedIntsIndexedWriter writer = new CompressedIntsIndexedWriter(ioPeon, "test", chunkFactor, byteOrder,
            compressionStrategy);/*from w w w  .ja  v a 2s  .  co  m*/
    CompressedIntsIndexedSupplier supplierFromList = CompressedIntsIndexedSupplier.fromList(Ints.asList(vals),
            chunkFactor, byteOrder, compressionStrategy);
    writer.open();
    for (int val : vals) {
        writer.add(val);
    }
    writer.close();
    long writtenLength = writer.getSerializedSize();
    final WritableByteChannel outputChannel = Channels.newChannel(ioPeon.makeOutputStream("output"));
    writer.writeToChannel(outputChannel);
    outputChannel.close();

    assertEquals(writtenLength, supplierFromList.getSerializedSize());

    // read from ByteBuffer and check values
    CompressedIntsIndexedSupplier supplierFromByteBuffer = CompressedIntsIndexedSupplier
            .fromByteBuffer(ByteBuffer.wrap(IOUtils.toByteArray(ioPeon.makeInputStream("output"))), byteOrder);
    IndexedInts indexedInts = supplierFromByteBuffer.get();
    assertEquals(vals.length, indexedInts.size());
    for (int i = 0; i < vals.length; ++i) {
        assertEquals(vals[i], indexedInts.get(i));
    }
    CloseQuietly.close(indexedInts);
}

From source file:org.springframework.boot.devtools.tunnel.payload.HttpTunnelPayload.java

/**
 * Assign this payload to the given {@link HttpOutputMessage}.
 * @param message the message to assign this payload to
 * @throws IOException in case of I/O errors
 *///from w ww.  j  av  a 2 s .c  o  m
public void assignTo(HttpOutputMessage message) throws IOException {
    Assert.notNull(message, "Message must not be null");
    HttpHeaders headers = message.getHeaders();
    headers.setContentLength(this.data.remaining());
    headers.add(SEQ_HEADER, Long.toString(getSequence()));
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    WritableByteChannel body = Channels.newChannel(message.getBody());
    while (this.data.hasRemaining()) {
        body.write(this.data);
    }
    body.close();
}

From source file:io.druid.segment.data.CompressedVSizeIndexedV3WriterTest.java

private void checkSerializedSizeAndData(int offsetChunkFactor, int valueChunkFactor) throws Exception {
    int maxValue = vals.size() > 0 ? getMaxValue(vals) : 0;
    CompressedIntsIndexedWriter offsetWriter = new CompressedIntsIndexedWriter(ioPeon, "offset",
            offsetChunkFactor, byteOrder, compressionStrategy);
    CompressedVSizeIntsIndexedWriter valueWriter = new CompressedVSizeIntsIndexedWriter(ioPeon, "value",
            maxValue, valueChunkFactor, byteOrder, compressionStrategy);
    CompressedVSizeIndexedV3Writer writer = new CompressedVSizeIndexedV3Writer(offsetWriter, valueWriter);
    CompressedVSizeIndexedV3Supplier supplierFromIterable = CompressedVSizeIndexedV3Supplier
            .fromIterable(Iterables.transform(vals, new Function<int[], IndexedInts>() {
                @Nullable//from w  w  w  . jav a 2  s .  c o  m
                @Override
                public IndexedInts apply(@Nullable final int[] input) {
                    return new ArrayBasedIndexedInts(input);
                }
            }), offsetChunkFactor, maxValue, byteOrder, compressionStrategy);
    writer.open();
    for (int[] val : vals) {
        writer.add(val);
    }
    writer.close();
    long writtenLength = writer.getSerializedSize();
    final WritableByteChannel outputChannel = Channels.newChannel(ioPeon.makeOutputStream("output"));
    writer.writeToChannel(outputChannel);
    outputChannel.close();

    assertEquals(writtenLength, supplierFromIterable.getSerializedSize());

    // read from ByteBuffer and check values
    CompressedVSizeIndexedV3Supplier supplierFromByteBuffer = CompressedVSizeIndexedV3Supplier
            .fromByteBuffer(ByteBuffer.wrap(IOUtils.toByteArray(ioPeon.makeInputStream("output"))), byteOrder);
    IndexedMultivalue<IndexedInts> indexedMultivalue = supplierFromByteBuffer.get();
    assertEquals(indexedMultivalue.size(), vals.size());
    for (int i = 0; i < vals.size(); ++i) {
        IndexedInts subVals = indexedMultivalue.get(i);
        assertEquals(subVals.size(), vals.get(i).length);
        for (int j = 0; j < subVals.size(); ++j) {
            assertEquals(subVals.get(j), vals.get(i)[j]);
        }
    }
    CloseQuietly.close(indexedMultivalue);
}

From source file:com.vmware.photon.controller.deployer.deployengine.DockerProvisioner.java

public void createImageFromTar(String filePath, String imageName) {
    if (StringUtils.isBlank(imageName)) {
        throw new IllegalArgumentException("imageName field cannot be null or blank");
    }/* www  .j a v a2 s. c o  m*/
    if (StringUtils.isBlank(filePath)) {
        throw new IllegalArgumentException("filePath field cannot be null or blank");
    }

    File tarFile = new File(filePath);
    try (FileInputStream fileInputStream = new FileInputStream(tarFile)) {
        FileChannel in = fileInputStream.getChannel();

        String endpoint = getImageLoadEndpoint();
        URL url = new URL(endpoint);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept", "application/json");
        connection.setDoOutput(true);
        WritableByteChannel out = Channels.newChannel(connection.getOutputStream());
        in.transferTo(0, tarFile.length(), out);
        in.close();
        out.close();

        int responseCode = connection.getResponseCode();
        if (!String.valueOf(responseCode).startsWith("2")) {
            throw new RuntimeException(
                    "Docker Endpoint cannot load image from tar. Failed with response code " + responseCode);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}