Example usage for java.nio ByteBuffer allocate

List of usage examples for java.nio ByteBuffer allocate

Introduction

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

Prototype

public static ByteBuffer allocate(int capacity) 

Source Link

Document

Creates a byte buffer based on a newly allocated byte array.

Usage

From source file:Test.java

public static void main(String args[]) throws Exception {
    ExecutorService pool = new ScheduledThreadPoolExecutor(3);
    AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(Paths.get("data.txt"),
            EnumSet.of(StandardOpenOption.READ), pool);
    CompletionHandler<Integer, ByteBuffer> handler = new CompletionHandler<Integer, ByteBuffer>() {
        @Override//from w ww. j  a  va 2  s  .  c o  m
        public synchronized void completed(Integer result, ByteBuffer attachment) {
            for (int i = 0; i < attachment.limit(); i++) {
                System.out.println((char) attachment.get(i));
            }
        }

        @Override
        public void failed(Throwable e, ByteBuffer attachment) {
        }
    };
    final int bufferCount = 5;
    ByteBuffer buffers[] = new ByteBuffer[bufferCount];
    for (int i = 0; i < bufferCount; i++) {
        buffers[i] = ByteBuffer.allocate(10);
        fileChannel.read(buffers[i], i * 10, buffers[i], handler);
    }
    pool.awaitTermination(1, TimeUnit.SECONDS);
    for (ByteBuffer byteBuffer : buffers) {
        for (int i = 0; i < byteBuffer.limit(); i++) {
            System.out.print((char) byteBuffer.get(i));
        }
    }
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Selector selector = Selector.open();

    ServerSocketChannel ssChannel1 = ServerSocketChannel.open();
    ssChannel1.configureBlocking(false);
    ssChannel1.socket().bind(new InetSocketAddress(80));

    ServerSocketChannel ssChannel2 = ServerSocketChannel.open();
    ssChannel2.configureBlocking(false);
    ssChannel2.socket().bind(new InetSocketAddress(81));

    ssChannel1.register(selector, SelectionKey.OP_ACCEPT);
    ssChannel2.register(selector, SelectionKey.OP_ACCEPT);

    while (true) {
        selector.select();/*  w  ww . jav a2  s  . c o  m*/
        Iterator it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey selKey = (SelectionKey) it.next();
            it.remove();

            if (selKey.isAcceptable()) {
                ServerSocketChannel ssChannel = (ServerSocketChannel) selKey.channel();
                SocketChannel sc = ssChannel.accept();
                ByteBuffer bb = ByteBuffer.allocate(100);
                sc.read(bb);

            }
        }
    }
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Selector selector = Selector.open();

    ServerSocketChannel ssChannel1 = ServerSocketChannel.open();
    ssChannel1.configureBlocking(false);
    ssChannel1.socket().bind(new InetSocketAddress(80));

    ServerSocketChannel ssChannel2 = ServerSocketChannel.open();
    ssChannel2.configureBlocking(false);
    ssChannel2.socket().bind(new InetSocketAddress(81));

    ssChannel1.register(selector, SelectionKey.OP_ACCEPT);
    ssChannel2.register(selector, SelectionKey.OP_ACCEPT);

    while (true) {
        selector.select();//from   ww w  .  java2s .c om
        Iterator it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey selKey = (SelectionKey) it.next();
            it.remove();

            if (selKey.isAcceptable()) {
                ServerSocketChannel ssChannel = (ServerSocketChannel) selKey.channel();
                SocketChannel sc = ssChannel.accept();
                ByteBuffer buf = ByteBuffer.allocate(100);
                int numBytesRead = sc.read(buf);

                if (numBytesRead == -1) {
                    sc.close();
                } else {
                    // Read the bytes from the buffer
                }
                int numBytesWritten = sc.write(buf);
            }
        }
    }
}

From source file:Lock.java

public static void main(String args[]) throws IOException, InterruptedException {
    RandomAccessFile file = null; // The file we'll lock
    FileChannel f = null; // The channel to the file
    FileLock lock = null; // The lock object we hold

    try { // The finally clause closes the channel and releases the lock
        // We use a temporary file as the lock file.
        String tmpdir = System.getProperty("java.io.tmpdir");
        String filename = Lock.class.getName() + ".lock";
        File lockfile = new File(tmpdir, filename);

        // Create a FileChannel that can read and write that file.
        // Note that we rely on the java.io package to open the file,
        // in read/write mode, and then just get a channel from it.
        // This will create the file if it doesn't exit. We'll arrange
        // for it to be deleted below, if we succeed in locking it.
        file = new RandomAccessFile(lockfile, "rw");
        f = file.getChannel();//from   ww w. j a v a  2s  . c o m

        // Try to get an exclusive lock on the file.
        // This method will return a lock or null, but will not block.
        // See also FileChannel.lock() for a blocking variant.
        lock = f.tryLock();

        if (lock != null) {
            // We obtained the lock, so arrange to delete the file when
            // we're done, and then write the approximate time at which
            // we'll relinquish the lock into the file.
            lockfile.deleteOnExit(); // Just a temporary file

            // First, we need a buffer to hold the timestamp
            ByteBuffer bytes = ByteBuffer.allocate(8); // a long is 8 bytes

            // Put the time in the buffer and flip to prepare for writing
            // Note that many Buffer methods can be "chained" like this.
            bytes.putLong(System.currentTimeMillis() + 10000).flip();

            f.write(bytes); // Write the buffer contents to the channel
            f.force(false); // Force them out to the disk
        } else {
            // We didn't get the lock, which means another instance is
            // running. First, let the user know this.
            System.out.println("Another instance is already running");

            // Next, we attempt to read the file to figure out how much
            // longer the other instance will be running. Since we don't
            // have a lock, the read may fail or return inconsistent data.
            try {
                ByteBuffer bytes = ByteBuffer.allocate(8);
                f.read(bytes); // Read 8 bytes from the file
                bytes.flip(); // Flip buffer before extracting bytes
                long exittime = bytes.getLong(); // Read bytes as a long
                // Figure out how long that time is from now and round
                // it to the nearest second.
                long secs = (exittime - System.currentTimeMillis() + 500) / 1000;
                // And tell the user about it.
                System.out.println("Try again in about " + secs + " seconds");
            } catch (IOException e) {
                // This probably means that locking is enforced by the OS
                // and we were prevented from reading the file.
            }

            // This is an abnormal exit, so set an exit code.
            System.exit(1);
        }

        // Simulate a real application by sleeping for 10 seconds.
        System.out.println("Starting...");
        Thread.sleep(10000);
        System.out.println("Exiting.");
    } finally {
        // Always release the lock and close the file
        // Closing the RandomAccessFile also closes its FileChannel.
        if (lock != null && lock.isValid())
            lock.release();
        if (file != null)
            file.close();
    }
}

From source file:DaytimeServer.java

public static void main(String args[]) {
    try { // Handle startup exceptions at the end of this block
        // Get an encoder for converting strings to bytes
        CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder();

        // Allow an alternative port for testing with non-root accounts
        int port = 13; // RFC867 specifies this port.
        if (args.length > 0)
            port = Integer.parseInt(args[0]);

        // The port we'll listen on
        SocketAddress localport = new InetSocketAddress(port);

        // Create and bind a tcp channel to listen for connections on.
        ServerSocketChannel tcpserver = ServerSocketChannel.open();
        tcpserver.socket().bind(localport);

        // Also create and bind a DatagramChannel to listen on.
        DatagramChannel udpserver = DatagramChannel.open();
        udpserver.socket().bind(localport);

        // Specify non-blocking mode for both channels, since our
        // Selector object will be doing the blocking for us.
        tcpserver.configureBlocking(false);
        udpserver.configureBlocking(false);

        // The Selector object is what allows us to block while waiting
        // for activity on either of the two channels.
        Selector selector = Selector.open();

        // Register the channels with the selector, and specify what
        // conditions (a connection ready to accept, a datagram ready
        // to read) we'd like the Selector to wake up for.
        // These methods return SelectionKey objects, which we don't
        // need to retain in this example.
        tcpserver.register(selector, SelectionKey.OP_ACCEPT);
        udpserver.register(selector, SelectionKey.OP_READ);

        // This is an empty byte buffer to receive emtpy datagrams with.
        // If a datagram overflows the receive buffer size, the extra bytes
        // are automatically discarded, so we don't have to worry about
        // buffer overflow attacks here.
        ByteBuffer receiveBuffer = ByteBuffer.allocate(0);

        // Now loop forever, processing client connections
        for (;;) {
            try { // Handle per-connection problems below
                // Wait for a client to connect
                selector.select();//from  w w w.j av  a2s.  co  m

                // If we get here, a client has probably connected, so
                // put our response into a ByteBuffer.
                String date = new java.util.Date().toString() + "\r\n";
                ByteBuffer response = encoder.encode(CharBuffer.wrap(date));

                // Get the SelectionKey objects for the channels that have
                // activity on them. These are the keys returned by the
                // register() methods above. They are returned in a
                // java.util.Set.
                Set keys = selector.selectedKeys();

                // Iterate through the Set of keys.
                for (Iterator i = keys.iterator(); i.hasNext();) {
                    // Get a key from the set, and remove it from the set
                    SelectionKey key = (SelectionKey) i.next();
                    i.remove();

                    // Get the channel associated with the key
                    Channel c = (Channel) key.channel();

                    // Now test the key and the channel to find out
                    // whether something happend on the TCP or UDP channel
                    if (key.isAcceptable() && c == tcpserver) {
                        // A client has attempted to connect via TCP.
                        // Accept the connection now.
                        SocketChannel client = tcpserver.accept();
                        // If we accepted the connection successfully,
                        // the send our respone back to the client.
                        if (client != null) {
                            client.write(response); // send respone
                            client.close(); // close connection
                        }
                    } else if (key.isReadable() && c == udpserver) {
                        // A UDP datagram is waiting. Receive it now,
                        // noting the address it was sent from.
                        SocketAddress clientAddress = udpserver.receive(receiveBuffer);
                        // If we got the datagram successfully, send
                        // the date and time in a response packet.
                        if (clientAddress != null)
                            udpserver.send(response, clientAddress);
                    }
                }
            } catch (java.io.IOException e) {
                // This is a (hopefully transient) problem with a single
                // connection: we log the error, but continue running.
                // We use our classname for the logger so that a sysadmin
                // can configure logging for this server independently
                // of other programs.
                Logger l = Logger.getLogger(DaytimeServer.class.getName());
                l.log(Level.WARNING, "IOException in DaytimeServer", e);
            } catch (Throwable t) {
                // If anything else goes wrong (out of memory, for example)
                // then log the problem and exit.
                Logger l = Logger.getLogger(DaytimeServer.class.getName());
                l.log(Level.SEVERE, "FATAL error in DaytimeServer", t);
                System.exit(1);
            }
        }
    } catch (Exception e) {
        // This is a startup error: there is no need to log it;
        // just print a message and exit
        System.err.println(e);
        System.exit(1);
    }
}

From source file:com.example.java.collections.ArrayExample.java

public static void main(String[] args) {

    /* ########################################################### */
    // Initializing an Array
    String[] creatures = { "goldfish", "oscar", "guppy", "minnow" };
    int[] numbers = new int[10];
    int counter = 0;
    while (counter < numbers.length) {
        numbers[counter] = counter;//from  w ww.j ava  2  s .c  o m
        System.out.println("number[" + counter + "]: " + counter);
        counter++;
    }
    for (int theInt : numbers) {
        System.out.println(theInt);
    }
    //System.out.println(numbers[numbers.length]);
    /* ########################################################### */

    /* ########################################################### */
    // Using Charecter Array
    String name = "Michael";
    // Charecter Array
    char[] charName = name.toCharArray();
    System.out.println(charName);

    // Array Fuctions
    char[] html = new char[] { 'M', 'i', 'c', 'h', 'a', 'e', 'l' };
    char[] lastFour = new char[4];
    System.arraycopy(html, 3, lastFour, 0, lastFour.length);
    System.out.println(lastFour);
    /* ########################################################### */

    /* ########################################################### */
    // Using Arrays of Other Types
    Object[] person = new Object[] { "Michael", new Integer(94), new Integer(1), new Date() };

    String fname = (String) person[0]; //ok
    Integer age = (Integer) person[1]; //ok
    Date start = (Date) person[2]; //oops!
    /* ########################################################### */

    /* ########################################################### */
    // Muti Dimestional Array
    String[][] bits = { { "Michael", "Ernest", "MFE" }, { "Ernest", "Friedman-Hill", "EFH" },
            { "Kathi", "Duggan", "KD" }, { "Jeff", "Kellum", "JK" } };

    bits[0] = new String[] { "Rudy", "Polanski", "RP" };
    bits[1] = new String[] { "Rudy", "Washington", "RW" };
    bits[2] = new String[] { "Rudy", "O'Reilly", "RO" };
    /* ########################################################### */

    /* ########################################################### */
    //Create ArrayList from array
    String[] stringArray = { "a", "b", "c", "d", "e" };
    ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray));
    System.out.println(arrayList);
    // [a, b, c, d, e]
    /* ########################################################### */

    /* ########################################################### */
    //Check if an array contains a certain value
    String[] stringArray1 = { "a", "b", "c", "d", "e" };
    boolean b = Arrays.asList(stringArray).contains("a");
    System.out.println(b);
    // true
    /* ########################################################### */

    /* ########################################################### */
    //Concatenate two arrays
    int[] intArray = { 1, 2, 3, 4, 5 };
    int[] intArray2 = { 6, 7, 8, 9, 10 };
    // Apache Commons Lang library
    int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2);
    /* ########################################################### */

    /* ########################################################### */
    //Joins the elements of the provided array into a single String
    // Apache common lang
    String j = StringUtils.join(new String[] { "a", "b", "c" }, ", ");
    System.out.println(j);
    // a, b, c
    /* ########################################################### */

    /* ########################################################### */
    //Covnert ArrayList to Array
    String[] stringArray3 = { "a", "b", "c", "d", "e" };
    ArrayList<String> arrayList1 = new ArrayList<String>(Arrays.asList(stringArray));
    String[] stringArr = new String[arrayList.size()];
    arrayList.toArray(stringArr);
    for (String s : stringArr) {
        System.out.println(s);
    }
    /* ########################################################### */

    /* ########################################################### */
    //Convert Array to Set
    Set<String> set = new HashSet<String>(Arrays.asList(stringArray));
    System.out.println(set);
    //[d, e, b, c, a]
    /* ########################################################### */

    /* ########################################################### */
    //Reverse an array
    int[] intArray1 = { 1, 2, 3, 4, 5 };
    ArrayUtils.reverse(intArray1);
    System.out.println(Arrays.toString(intArray1));
    //[5, 4, 3, 2, 1]
    /* ########################################################### */

    /* ########################################################### */
    // Remove element of an array
    int[] intArray3 = { 1, 2, 3, 4, 5 };
    int[] removed = ArrayUtils.removeElement(intArray3, 3);//create a new array
    System.out.println(Arrays.toString(removed));
    /* ########################################################### */

    /* ########################################################### */
    byte[] bytes = ByteBuffer.allocate(4).putInt(8).array();
    for (byte t : bytes) {
        System.out.format("0x%x ", t);
    }
    /* ########################################################### */

}

From source file:Main.java

public static byte[] getInt(int a) {
    return ByteBuffer.allocate(4).putInt(a).array();
}

From source file:Main.java

public static byte[] getChar(char c) {
    return ByteBuffer.allocate(2).putChar(c).array();
}

From source file:Main.java

protected static byte[] getBytes(int i) {
    return ByteBuffer.allocate(Integer.SIZE / 8).putInt(i).array();
}

From source file:Main.java

public static byte[] floatToByte(float value) {
    return ByteBuffer.allocate(4).putFloat(value).array();
}