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

public static void main(String[] args) throws Exception {
    String fromFileName = "from.txt";
    String toFileName = "to.txt";
    FileChannel in = new FileInputStream(fromFileName).getChannel();
    FileChannel out = new FileOutputStream(toFileName).getChannel();

    ByteBuffer buff = ByteBuffer.allocateDirect(32 * 1024);

    while (in.read(buff) > 0) {
        buff.flip();//from www .j av a 2s .co m
        out.write(buff);
        buff.clear();
    }

    in.close();
    out.close();
}

From source file:MainClass.java

public static void main(String args[]) {
    FileOutputStream fileOutputStream;
    FileChannel fileChannel;//from   w w w  . j  ava 2s .  c  o m
    ByteBuffer byteBuffer;

    try {
        fileOutputStream = new FileOutputStream("test.txt");
        fileChannel = fileOutputStream.getChannel();
        byteBuffer = ByteBuffer.allocateDirect(26);

        for (int i = 0; i < 26; i++)
            byteBuffer.put((byte) ('A' + i));
        byteBuffer.rewind();
        fileChannel.write(byteBuffer);
        fileChannel.close();
        fileOutputStream.close();
    } catch (IOException exc) {
        System.out.println(exc);
    }
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    DatagramChannel channel = DatagramChannel.open();
    DatagramSocket socket = channel.socket();
    SocketAddress address = new InetSocketAddress(9999);
    socket.bind(address);/*  w w  w  . ja  v  a  2  s .c  om*/
    ByteBuffer buffer = ByteBuffer.allocateDirect(65507);
    while (true) {
        SocketAddress client = channel.receive(buffer);
        buffer.flip();
        channel.send(buffer, client);
        buffer.clear();
    }
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    // Create a ByteBuffer using a byte array
    byte[] bytes = new byte[10];
    ByteBuffer buffer = ByteBuffer.wrap(bytes);

    // Create a non-direct ByteBuffer with a 10 byte capacity
    // The underlying storage is a byte array.
    buffer = ByteBuffer.allocate(10);

    // Create a memory-mapped ByteBuffer with a 10 byte capacity.
    buffer = ByteBuffer.allocateDirect(10);
}

From source file:GetWebPageDemo.java

public static void main(String args[]) throws Exception {
    String resource, host, file;//w  ww.  j a v  a  2s .c  o  m
    int slashPos;

    resource = "www.java2s.com/index.htm";
    slashPos = resource.indexOf('/'); // find host/file separator
    if (slashPos < 0) {
        resource = resource + "/";
        slashPos = resource.indexOf('/');
    }
    file = resource.substring(slashPos); // isolate host and file parts
    host = resource.substring(0, slashPos);
    System.out.println("Host to contact: '" + host + "'");
    System.out.println("File to fetch : '" + file + "'");

    SocketChannel channel = null;

    try {
        Charset charset = Charset.forName("ISO-8859-1");
        CharsetDecoder decoder = charset.newDecoder();
        CharsetEncoder encoder = charset.newEncoder();

        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
        CharBuffer charBuffer = CharBuffer.allocate(1024);

        InetSocketAddress socketAddress = new InetSocketAddress(host, 80);
        channel = SocketChannel.open();
        channel.connect(socketAddress);

        String request = "GET " + file + " \r\n\r\n";
        channel.write(encoder.encode(CharBuffer.wrap(request)));

        while ((channel.read(buffer)) != -1) {
            buffer.flip();
            decoder.decode(buffer, charBuffer, false);
            charBuffer.flip();
            System.out.println(charBuffer);
            buffer.clear();
            charBuffer.clear();
        }
    } catch (UnknownHostException e) {
        System.err.println(e);
    } catch (IOException e) {
        System.err.println(e);
    } finally {
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException ignored) {
            }
        }
    }

    System.out.println("\nDone.");
}

From source file:GetWebPageApp.java

public static void main(String args[]) throws Exception {
    String resource, host, file;//from   w w  w. j  av  a2s. c o m
    int slashPos;

    resource = "www.java2s.com/index.htm"; // skip HTTP://
    slashPos = resource.indexOf('/'); // find host/file separator
    if (slashPos < 0) {
        resource = resource + "/";
        slashPos = resource.indexOf('/');
    }
    file = resource.substring(slashPos); // isolate host and file parts
    host = resource.substring(0, slashPos);
    System.out.println("Host to contact: '" + host + "'");
    System.out.println("File to fetch : '" + file + "'");

    SocketChannel channel = null;

    try {
        Charset charset = Charset.forName("ISO-8859-1");
        CharsetDecoder decoder = charset.newDecoder();
        CharsetEncoder encoder = charset.newEncoder();

        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
        CharBuffer charBuffer = CharBuffer.allocate(1024);

        InetSocketAddress socketAddress = new InetSocketAddress(host, 80);
        channel = SocketChannel.open();
        channel.configureBlocking(false);
        channel.connect(socketAddress);

        selector = Selector.open();

        channel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ);

        while (selector.select(500) > 0) {
            Set readyKeys = selector.selectedKeys();
            try {
                Iterator readyItor = readyKeys.iterator();

                while (readyItor.hasNext()) {

                    SelectionKey key = (SelectionKey) readyItor.next();
                    readyItor.remove();
                    SocketChannel keyChannel = (SocketChannel) key.channel();

                    if (key.isConnectable()) {
                        if (keyChannel.isConnectionPending()) {
                            keyChannel.finishConnect();
                        }
                        String request = "GET " + file + " \r\n\r\n";
                        keyChannel.write(encoder.encode(CharBuffer.wrap(request)));
                    } else if (key.isReadable()) {
                        keyChannel.read(buffer);
                        buffer.flip();

                        decoder.decode(buffer, charBuffer, false);
                        charBuffer.flip();
                        System.out.print(charBuffer);

                        buffer.clear();
                        charBuffer.clear();

                    } else {
                        System.err.println("Unknown key");
                    }
                }
            } catch (ConcurrentModificationException e) {
            }
        }
    } catch (UnknownHostException e) {
        System.err.println(e);
    } catch (IOException e) {
        System.err.println(e);
    } finally {
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException ignored) {
            }
        }
    }
    System.out.println("\nDone.");
}

From source file:org.apache.commons.crypto.examples.CipherByteBufferExample.java

public static void main(String[] args) throws Exception {
    final SecretKeySpec key = new SecretKeySpec(getUTF8Bytes("1234567890123456"), "AES");
    final IvParameterSpec iv = new IvParameterSpec(getUTF8Bytes("1234567890123456"));
    Properties properties = new Properties();
    //Creates a CryptoCipher instance with the transformation and properties.
    final String transform = "AES/CBC/PKCS5Padding";
    final ByteBuffer outBuffer;
    final int bufferSize = 1024;
    final int updateBytes;
    final int finalBytes;
    try (CryptoCipher encipher = Utils.getCipherInstance(transform, properties)) {

        ByteBuffer inBuffer = ByteBuffer.allocateDirect(bufferSize);
        outBuffer = ByteBuffer.allocateDirect(bufferSize);
        inBuffer.put(getUTF8Bytes("hello world!"));

        inBuffer.flip(); // ready for the cipher to read it
        // Show the data is there
        System.out.println("inBuffer=" + asString(inBuffer));

        // Initializes the cipher with ENCRYPT_MODE,key and iv.
        encipher.init(Cipher.ENCRYPT_MODE, key, iv);
        // Continues a multiple-part encryption/decryption operation for byte buffer.
        updateBytes = encipher.update(inBuffer, outBuffer);
        System.out.println(updateBytes);

        // We should call do final at the end of encryption/decryption.
        finalBytes = encipher.doFinal(inBuffer, outBuffer);
        System.out.println(finalBytes);
    }/*w ww .ja v a2  s . c  o m*/

    outBuffer.flip(); // ready for use as decrypt
    byte[] encoded = new byte[updateBytes + finalBytes];
    outBuffer.duplicate().get(encoded);
    System.out.println(Arrays.toString(encoded));

    // Now reverse the process
    try (CryptoCipher decipher = Utils.getCipherInstance(transform, properties)) {
        decipher.init(Cipher.DECRYPT_MODE, key, iv);
        ByteBuffer decoded = ByteBuffer.allocateDirect(bufferSize);
        decipher.update(outBuffer, decoded);
        decipher.doFinal(outBuffer, decoded);
        decoded.flip(); // ready for use
        System.out.println("decoded=" + asString(decoded));
    }
}

From source file:PrintServiceWebInterface.java

public static void main(String[] args) throws IOException {
    // Get the character encoders and decoders we'll need
    Charset charset = Charset.forName("ISO-8859-1");
    CharsetEncoder encoder = charset.newEncoder();

    // The HTTP headers we send back to the client are fixed
    String headers = "HTTP/1.1 200 OK\r\n" + "Content-type: text/html\r\n" + "Connection: close\r\n" + "\r\n";

    // We'll use two buffers in our response. One holds the fixed
    // headers, and the other holds the variable body of the response.
    ByteBuffer[] buffers = new ByteBuffer[2];
    buffers[0] = encoder.encode(CharBuffer.wrap(headers));
    ByteBuffer body = ByteBuffer.allocateDirect(16 * 1024);
    buffers[1] = body;/* ww w  . j a  va 2s .  c  om*/

    // Find all available PrintService objects to describe
    PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);

    // All of the channels we use in this code will be in non-blocking
    // mode. So we create a Selector object that will block while
    // monitoring all of the channels and will only stop blocking when
    // one or more of the channels is ready for I/O of some sort.
    Selector selector = Selector.open();

    // Create a new ServerSocketChannel, and bind it to port 8000.
    // Note that we have to do this using the underlying ServerSocket.
    ServerSocketChannel server = ServerSocketChannel.open();
    server.socket().bind(new java.net.InetSocketAddress(8000));

    // Put the ServerSocketChannel into non-blocking mode
    server.configureBlocking(false);

    // Now register the channel with the Selector. The SelectionKey
    // represents the registration of this channel with this Selector.
    SelectionKey serverkey = server.register(selector, SelectionKey.OP_ACCEPT);

    for (;;) { // The main server loop. The server runs forever.
        // This call blocks until there is activity on one of the
        // registered channels. This is the key method in non-blocking I/O.
        selector.select();

        // Get a java.util.Set containing the SelectionKey objects for
        // all channels that are ready for I/O.
        Set keys = selector.selectedKeys();

        // Use a java.util.Iterator to loop through the selected keys
        for (Iterator i = keys.iterator(); i.hasNext();) {
            // Get the next SelectionKey in the set, and then remove it
            // from the set. It must be removed explicitly, or it will
            // be returned again by the next call to select().
            SelectionKey key = (SelectionKey) i.next();
            i.remove();

            // Check whether this key is the SelectionKey we got when
            // we registered the ServerSocketChannel.
            if (key == serverkey) {
                // Activity on the ServerSocketChannel means a client
                // is trying to connect to the server.
                if (key.isAcceptable()) {
                    // Accept the client connection, and obtain a
                    // SocketChannel to communicate with the client.
                    SocketChannel client = server.accept();

                    // Make sure we actually got a connection
                    if (client == null)
                        continue;

                    // Put the client channel in non-blocking mode.
                    client.configureBlocking(false);

                    // Now register the client channel with the Selector,
                    // specifying that we'd like to know when there is
                    // data ready to read on the channel.
                    SelectionKey clientkey = client.register(selector, SelectionKey.OP_READ);
                }
            } else {
                // If the key we got from the Set of keys is not the
                // ServerSocketChannel key, then it must be a key
                // representing one of the client connections.
                // Get the channel from the key.
                SocketChannel client = (SocketChannel) key.channel();

                // If we got here, it should mean that there is data to
                // be read from the channel, but we double-check here.
                if (!key.isReadable())
                    continue;

                // Now read bytes from the client. We assume that
                // we get all the client's bytes in one read operation
                client.read(body);

                // The data we read should be some kind of HTTP GET
                // request. We don't bother checking it however since
                // there is only one page of data we know how to return.
                body.clear();

                // Build an HTML document as our reponse.
                // The body of the document contains PrintService details
                StringBuffer response = new StringBuffer();
                response.append(
                        "<html><head><title>Printer Status</title></head>" + "<body><h1>Printer Status</h1>");
                for (int s = 0; s < services.length; s++) {
                    PrintService service = services[s];
                    response.append("<h2>").append(service.getName()).append("</h2><table>");
                    Attribute[] attrs = service.getAttributes().toArray();
                    for (int a = 0; a < attrs.length; a++) {
                        Attribute attr = attrs[a];
                        response.append("<tr><td>").append(attr.getName()).append("</td><td>").append(attr)
                                .append("</tr>");
                    }
                    response.append("</table>");
                }
                response.append("</body></html>\r\n");

                // Encode the response into the body ByteBuffer
                encoder.reset();
                encoder.encode(CharBuffer.wrap(response), body, true);
                encoder.flush(body);

                body.flip(); // Prepare the body buffer to be drained
                // While there are bytes left to write
                while (body.hasRemaining()) {
                    // Write both header and body buffers
                    client.write(buffers);
                }
                buffers[0].flip(); // Prepare header buffer for next write
                body.clear(); // Prepare body buffer for next read

                // Once we've sent our response, we have no more interest
                // in the client channel or its SelectionKey
                client.close(); // Close the channel.
                key.cancel(); // Tell Selector to stop monitoring it.
            }
        }
    }
}

From source file:HttpGet.java

public static void main(String[] args) {
    SocketChannel server = null; // Channel for reading from server
    FileOutputStream outputStream = null; // Stream to destination file
    WritableByteChannel destination; // Channel to write to it

    try { // Exception handling and channel closing code follows this block

        // Parse the URL. Note we use the new java.net.URI, not URL here.
        URI uri = new URI(args[0]);

        // Now query and verify the various parts of the URI
        String scheme = uri.getScheme();
        if (scheme == null || !scheme.equals("http"))
            throw new IllegalArgumentException("Must use 'http:' protocol");

        String hostname = uri.getHost();

        int port = uri.getPort();
        if (port == -1)
            port = 80; // Use default port if none specified

        String path = uri.getRawPath();
        if (path == null || path.length() == 0)
            path = "/";

        String query = uri.getRawQuery();
        query = (query == null) ? "" : '?' + query;

        // Combine the hostname and port into a single address object.
        // java.net.SocketAddress and InetSocketAddress are new in Java 1.4
        SocketAddress serverAddress = new InetSocketAddress(hostname, port);

        // Open a SocketChannel to the server
        server = SocketChannel.open(serverAddress);

        // Put together the HTTP request we'll send to the server.
        String request = "GET " + path + query + " HTTP/1.1\r\n" + // The request
                "Host: " + hostname + "\r\n" + // Required in HTTP 1.1
                "Connection: close\r\n" + // Don't keep connection open
                "User-Agent: " + HttpGet.class.getName() + "\r\n" + "\r\n"; // Blank
                                                                            // line
                                                                            // indicates
                                                                            // end of
                                                                            // request
                                                                            // headers

        // Now wrap a CharBuffer around that request string
        CharBuffer requestChars = CharBuffer.wrap(request);

        // Get a Charset object to encode the char buffer into bytes
        Charset charset = Charset.forName("ISO-8859-1");

        // Use the charset to encode the request into a byte buffer
        ByteBuffer requestBytes = charset.encode(requestChars);

        // Finally, we can send this HTTP request to the server.
        server.write(requestBytes);/*from   w  w w .  ja  v  a 2  s  . c  o  m*/

        // Set up an output channel to send the output to.
        if (args.length > 1) { // Use a specified filename
            outputStream = new FileOutputStream(args[1]);
            destination = outputStream.getChannel();
        } else
            // Or wrap a channel around standard out
            destination = Channels.newChannel(System.out);

        // Allocate a 32 Kilobyte byte buffer for reading the response.
        // Hopefully we'll get a low-level "direct" buffer
        ByteBuffer data = ByteBuffer.allocateDirect(32 * 1024);

        // Have we discarded the HTTP response headers yet?
        boolean skippedHeaders = false;
        // The code sent by the server
        int responseCode = -1;

        // Now loop, reading data from the server channel and writing it
        // to the destination channel until the server indicates that it
        // has no more data.
        while (server.read(data) != -1) { // Read data, and check for end
            data.flip(); // Prepare to extract data from buffer

            // All HTTP reponses begin with a set of HTTP headers, which
            // we need to discard. The headers end with the string
            // "\r\n\r\n", or the bytes 13,10,13,10. If we haven't already
            // skipped them then do so now.
            if (!skippedHeaders) {
                // First, though, read the HTTP response code.
                // Assume that we get the complete first line of the
                // response when the first read() call returns. Assume also
                // that the first 9 bytes are the ASCII characters
                // "HTTP/1.1 ", and that the response code is the ASCII
                // characters in the following three bytes.
                if (responseCode == -1) {
                    responseCode = 100 * (data.get(9) - '0') + 10 * (data.get(10) - '0')
                            + 1 * (data.get(11) - '0');

                    // If there was an error, report it and quit
                    // Note that we do not handle redirect responses.
                    if (responseCode < 200 || responseCode >= 300) {
                        System.err.println("HTTP Error: " + responseCode);
                        System.exit(1);
                    }
                }

                // Now skip the rest of the headers.
                try {
                    for (;;) {
                        if ((data.get() == 13) && (data.get() == 10) && (data.get() == 13)
                                && (data.get() == 10)) {
                            skippedHeaders = true;
                            break;
                        }
                    }
                } catch (BufferUnderflowException e) {
                    // If we arrive here, it means we reached the end of
                    // the buffer and didn't find the end of the headers.
                    // There is a chance that the last 1, 2, or 3 bytes in
                    // the buffer were the beginning of the \r\n\r\n
                    // sequence, so back up a bit.
                    data.position(data.position() - 3);
                    // Now discard the headers we have read
                    data.compact();
                    // And go read more data from the server.
                    continue;
                }
            }

            // Write the data out; drain the buffer fully.
            while (data.hasRemaining())
                destination.write(data);

            // Now that the buffer is drained, put it into fill mode
            // in preparation for reading more data into it.
            data.clear(); // data.compact() also works here
        }
    } catch (Exception e) { // Report any errors that arise
        System.err.println(e);
        System.err.println("Usage: java HttpGet <URL> [<filename>]");
    } finally { // Close the channels and output file stream, if needed
        try {
            if (server != null && server.isOpen())
                server.close();
            if (outputStream != null)
                outputStream.close();
        } catch (IOException e) {
        }
    }
}

From source file:Main.java

public static ByteBuffer makeByteBuffer(byte[] i_arr) {
    ByteBuffer bb = ByteBuffer.allocateDirect(i_arr.length);
    bb.put(i_arr);//from w w  w .  j  av a  2 s  .  co m
    bb.position(0);
    return bb;
}