Example usage for java.nio.channels WritableByteChannel write

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

Introduction

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

Prototype

public int write(ByteBuffer src) throws IOException;

Source Link

Document

Writes a sequence of bytes to this channel from the given buffer.

Usage

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

public void write(OutputStream output) throws IOException {

    baseBuffer.rewind();//from   www  .  j ava2 s .  co m
    checkBuffer.rewind();
    tailBuffer.rewind();

    int baseCheckSize = Math.min(maxBaseCheckIndex + 64, baseBuffer.capacity());
    int tailSize = Math.min(tailIndex - TAIL_OFFSET + 64, tailBuffer.capacity());

    DataOutputStream dataOutput = new DataOutputStream(new BufferedOutputStream(output));

    dataOutput.writeBoolean(compact);
    dataOutput.writeInt(baseCheckSize);
    dataOutput.writeInt(tailSize);

    WritableByteChannel channel = Channels.newChannel(dataOutput);

    ByteBuffer tmpBuffer = ByteBuffer.allocate(baseCheckSize * 4);
    IntBuffer tmpIntBuffer = tmpBuffer.asIntBuffer();
    tmpIntBuffer.put(baseBuffer.array(), 0, baseCheckSize);
    tmpBuffer.rewind();
    channel.write(tmpBuffer);

    tmpBuffer = ByteBuffer.allocate(baseCheckSize * 4);
    tmpIntBuffer = tmpBuffer.asIntBuffer();
    tmpIntBuffer.put(checkBuffer.array(), 0, baseCheckSize);
    tmpBuffer.rewind();
    channel.write(tmpBuffer);

    tmpBuffer = ByteBuffer.allocate(tailSize * 2);
    CharBuffer tmpCharBuffer = tmpBuffer.asCharBuffer();
    tmpCharBuffer.put(tailBuffer.array(), 0, tailSize);
    tmpBuffer.rewind();
    channel.write(tmpBuffer);

    dataOutput.flush();
}

From source file:org.itstechupnorth.walrus.base.ArticleBuffer.java

public WritableByteChannel saveTo(WritableByteChannel out) throws IOException {
    saving = true;/*from   www  . jav  a 2  s . com*/
    final int originalPosition = buffer.position();
    // System.out.println(moniker() + "saving@" + buffer.position());
    try {
        buffer.flip();
        encoder.reset();

        outBuffer.clear();
        boolean more = true;
        while (more) {
            final CoderResult result = encoder.encode(buffer, outBuffer, true);
            outBuffer.flip();
            out.write(outBuffer);
            outBuffer.clear();
            more = CoderResult.OVERFLOW.equals(result);
        }
        return out;
    } finally {
        buffer.clear();
        buffer.position(originalPosition);
        // System.out.println(moniker() + "saved@" + buffer.position());
        saving = false;
    }
}

From source file:com.github.jinahya.verbose.codec.BinaryCodecTest.java

protected final void encodeDecode(final ReadableByteChannel expectedChannel) throws IOException {

    if (expectedChannel == null) {
        throw new NullPointerException("null expectedChannel");
    }/*w ww  . j a v  a2 s. c  om*/

    final Path encodedPath = Files.createTempFile("test", null);
    getRuntime().addShutdownHook(new Thread(() -> {
        try {
            Files.delete(encodedPath);
        } catch (final IOException ioe) {
            ioe.printStackTrace(System.err);
        }
    }));
    final WritableByteChannel encodedChannel = FileChannel.open(encodedPath, StandardOpenOption.WRITE);

    final ByteBuffer decodedBuffer = ByteBuffer.allocate(128);
    final ByteBuffer encodedBuffer = ByteBuffer.allocate(decodedBuffer.capacity() << 1);

    while (expectedChannel.read(decodedBuffer) != -1) {
        decodedBuffer.flip(); // limit -> position; position -> zero
        encoder.encode(decodedBuffer, encodedBuffer);
        encodedBuffer.flip();
        encodedChannel.write(encodedBuffer);
        encodedBuffer.compact(); // position -> n  + 1; limit -> capacity
        decodedBuffer.compact();
    }

    decodedBuffer.flip();
    while (decodedBuffer.hasRemaining()) {
        encoder.encode(decodedBuffer, encodedBuffer);
        encodedBuffer.flip();
        encodedChannel.write(encodedBuffer);
        encodedBuffer.compact();
    }

    encodedBuffer.flip();
    while (encodedBuffer.hasRemaining()) {
        encodedChannel.write(encodedBuffer);
    }
}

From source file:oz.hadoop.yarn.api.FsByteBufferPersister.java

/**
 * /*w w w. j a  v a2 s  .c om*/
 * @param dataBuffer
 */
public void persist(String dataIdentifier, ByteBuffer dataBuffer) {
    WritableByteChannel outputChannel = this.outputChannels.get(dataIdentifier);
    if (outputChannel == null) {
        String fileName = this.generateFileName(dataIdentifier);
        try {
            OutputStream os = this.fileSystem.create(new Path(fileName), true);
            outputChannel = Channels.newChannel(os);
            this.outputChannels.put(dataIdentifier, outputChannel);
        } catch (Exception e) {
            throw new IllegalStateException(
                    "Failed to create FSDataOutputStream with fileIdentifier '" + dataIdentifier + "'", e);
        }
    }
    dataBuffer.rewind();
    try {
        outputChannel.write(dataBuffer);
    } catch (Exception e) {
        throw new IllegalStateException("Failed to write data to channel", e);
    }
}

From source file:org.wymiwyg.wrhapi.test.BaseTests.java

/**
 * @throws Exception/*w  w  w  .  j  a va2s  .  c om*/
 */
@Test
public void testLongBody() throws Exception {
    final byte[] body = Util.createRandomBytes(10 * 1000000);
    WebServer webServer = createServer().startNewWebServer(new Handler() {

        public void handle(Request request, Response response) throws HandlerException {
            log.info("handling testLongBody");
            response.setBody(new MessageBody2Write() {

                public void writeTo(WritableByteChannel out) throws IOException {
                    out.write(ByteBuffer.wrap(body));
                }
            });
        }
    }, serverBinding);

    try {
        URL serverURL = new URL("http://" + serverBinding.getInetAddress().getHostAddress() + ":"
                + serverBinding.getPort() + "/");
        InputStream reader = serverURL.openStream();
        ByteArrayOutputStream bout = new ByteArrayOutputStream(30 * 1000000);

        for (int ch = reader.read(); ch != -1; ch = reader.read()) {
            bout.write(ch);
        }

        byte[] returnedBytes = bout.toByteArray();

        for (int i = 0; i < body.length; i++) {
            assertEquals(body[i], returnedBytes[i]);
        }
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        webServer.stop();
    }
}

From source file:org.wymiwyg.wrhapi.test.BaseTests.java

private void testSimpleBody(final boolean writeBody) throws Exception {
    final String body = "This is the content of the body";
    WebServer webServer = createServer().startNewWebServer(new Handler() {

        public void handle(Request request, Response response) throws HandlerException {
            log.info("handling testSimpleBody");

            if (writeBody) {
                response.setBody(new MessageBody2Write() {

                    public void writeTo(WritableByteChannel out) throws IOException {
                        out.write(ByteBuffer.wrap(body.getBytes()));
                    }/*  ww w.jav a  2s. co m*/
                });
            } else {
                response.setBody(new MessageBody2Read() {

                    public ReadableByteChannel read() throws IOException {
                        return Channels.newChannel(new ByteArrayInputStream(body.getBytes()));
                    }
                });
            }
        }
    }, serverBinding);

    try {
        URL serverURL = new URL("http://" + serverBinding.getInetAddress().getHostAddress() + ":"
                + serverBinding.getPort() + "/");
        Reader reader = new InputStreamReader(serverURL.openStream());
        StringWriter stringWriter = new StringWriter();

        for (int ch = reader.read(); ch != -1; ch = reader.read()) {
            stringWriter.write(ch);
        }

        assertEquals(body, stringWriter.toString());
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        webServer.stop();
    }
}

From source file:com.google.cloud.hadoop.gcsio.GoogleCloudStorageIntegrationHelper.java

/**
 * Writes a file with the given buffer repeated numWrites times.
 *
 * @param bucketName name of the bucket to create object in
 * @param objectName name of the object to create
 * @param buffer Data to write//from  ww w .j a v  a2s .  c om
 * @param numWrites number of times to repeat the data
 * @return number of bytes written
 */
protected int writeFile(String bucketName, String objectName, ByteBuffer buffer, int numWrites)
        throws IOException {
    int numBytesWritten = -1;
    int totalBytesWritten = 0;
    WritableByteChannel writeChannel = null;

    try {
        writeChannel = create(bucketName, objectName, new CreateFileOptions(false /* overwrite existing */));
        for (int i = 0; i < numWrites; i++) {
            buffer.clear();
            numBytesWritten = writeChannel.write(buffer);
            Assert.assertEquals("could not write the entire buffer", buffer.capacity(), numBytesWritten);
            totalBytesWritten += numBytesWritten;
        }

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

    return totalBytesWritten;
}

From source file:org.apache.jackrabbit.oak.plugins.segment.Segment.java

/**
 * Writes this segment to the given output stream.
 *
 * @param stream stream to which this segment will be written
 * @throws IOException on an IO error//from w  ww  .j  ava  2 s  .  co m
 */
public void writeTo(OutputStream stream) throws IOException {
    ByteBuffer buffer = data.duplicate();
    WritableByteChannel channel = Channels.newChannel(stream);
    while (buffer.hasRemaining()) {
        channel.write(buffer);
    }
}