Example usage for java.nio ByteBuffer allocateDirect

List of usage examples for java.nio ByteBuffer allocateDirect

Introduction

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

Prototype

public static ByteBuffer allocateDirect(int capacity) 

Source Link

Document

Creates a direct byte buffer based on a newly allocated memory block.

Usage

From source file:au.org.theark.core.service.ArkCommonServiceImpl.java

/**
 * {@inheritDoc}//ww w.ja  v a2 s.co m
 */
public void copyArkLargeFileAttachments(String sourceFilePath, String destinationFilePath) throws IOException {
    FileChannel source = null;
    FileChannel destination = null;

    try {
        source = new FileInputStream(new File(sourceFilePath)).getChannel();
        destination = new FileOutputStream(new File(destinationFilePath)).getChannel();

        // This fails with Map Failed exception on large files
        // destination.transferFrom(source, 0, source.size());

        ByteBuffer buf = ByteBuffer.allocateDirect(DEFAULT_BUFFER_SIZE);
        while ((source.read(buf)) != -1) {
            buf.flip();
            destination.write(buf);
            buf.clear();
        }
    } finally {
        if (source != null) {
            source.close();
        }
        if (destination != null) {
            destination.close();
        }
    }
}

From source file:org.nd4j.linalg.Nd4jTestsC.java

@Test
public void testNullPointerDataBuffer() {
    DataBuffer.Type initialType = Nd4j.dataType();

    DataTypeUtil.setDTypeForContext(DataBuffer.Type.FLOAT);

    ByteBuffer allocate = ByteBuffer.allocateDirect(10 * 4).order(ByteOrder.nativeOrder());
    allocate.asFloatBuffer().put(new float[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
    DataBuffer buff = Nd4j.createBuffer(allocate, DataBuffer.Type.FLOAT, 10);
    float sum = Nd4j.create(buff).sumNumber().floatValue();
    System.out.println(sum);// www.  j ava 2  s . c  om
    assertEquals(55f, sum, 0.001f);

    DataTypeUtil.setDTypeForContext(initialType);
}

From source file:com.sonicle.webtop.mail.Service.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();//  www  . ja  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);
    }
}