Example usage for java.nio ByteBuffer wrap

List of usage examples for java.nio ByteBuffer wrap

Introduction

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

Prototype

public static ByteBuffer wrap(byte[] array) 

Source Link

Document

Creates a new byte buffer by wrapping the given byte array.

Usage

From source file:Test.java

License:asdf

public static void main(String[] args) throws IOException {
    Path path = Paths.get("/users.txt");

    final String newLine = System.getProperty("line.separator");
    try (SeekableByteChannel sbc = Files.newByteChannel(path, StandardOpenOption.WRITE)) {
        ByteBuffer buffer;/*  ww  w .j  av  a  2s.  c o m*/
        long position = sbc.size();
        sbc.position(position);
        System.out.println("Position: " + sbc.position());

        buffer = ByteBuffer.wrap((newLine + "asdf").getBytes());
        sbc.write(buffer);
        System.out.println("Position: " + sbc.position());
        buffer = ByteBuffer.wrap((newLine + "asdf").getBytes());
        sbc.write(buffer);
        System.out.println("Position: " + sbc.position());
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    DatagramChannel server = DatagramChannel.open();
    server.bind(null);//ww w  .  j a v  a 2 s .c o  m
    NetworkInterface interf = NetworkInterface.getByName(MULTICAST_INTERFACE_NAME);
    server.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);

    String msg = "Hello!";
    ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
    InetSocketAddress group = new InetSocketAddress(MULTICAST_IP, MULTICAST_PORT);

    server.send(buffer, group);
    System.out.println("Sent the   multicast  message: " + msg);
}

From source file:Test.java

public static void main(String[] args) throws Exception {

    AsynchronousSocketChannel client = AsynchronousSocketChannel.open();
    InetSocketAddress address = new InetSocketAddress("localhost", 5000);

    Future<Void> future = client.connect(address);
    System.out.println("Client: Waiting for the connection to complete");
    future.get();/* w  ww .  j a  va  2 s .com*/

    String message = "";
    while (!message.equals("quit")) {
        System.out.print("Enter a message: ");
        Scanner scanner = new Scanner(System.in);
        message = scanner.nextLine();
        System.out.println("Client: Sending ...");
        ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());
        System.out.println("Client: Message sent: " + new String(buffer.array()));
        client.write(buffer);
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    File aFile = new File("main.java");
    FileInputStream inFile = new FileInputStream(aFile);
    FileChannel inChannel = inFile.getChannel();
    ByteBuffer lengthBuf = ByteBuffer.allocate(8);
    while (true) {
        if (inChannel.read(lengthBuf) == -1) {
            break;
        }//from ww w.  j  av a  2 s .co m
        lengthBuf.flip();
        int strLength = (int) lengthBuf.getDouble();
        ByteBuffer buf = ByteBuffer.allocate(2 * strLength + 8);
        if (inChannel.read(buf) == -1) {
            break;
        }
        buf.flip();
        byte[] strChars = new byte[2 * strLength];
        buf.get(strChars);
        System.out.println(strLength);
        System.out.println(ByteBuffer.wrap(strChars).asCharBuffer());
        System.out.println(buf.getLong());
        lengthBuf.clear();
    }
    inFile.close();
}

From source file:MainClass.java

public static void main(String[] args) throws IOException {

    URL u = new URL("http://www.java2s.com");
    String host = u.getHost();/*  w w w  . j  a  v a2  s  .com*/
    int port = 80;
    String file = "/";

    SocketAddress remote = new InetSocketAddress(host, port);
    SocketChannel channel = SocketChannel.open(remote);
    FileOutputStream out = new FileOutputStream("yourfile.htm");
    FileChannel localFile = out.getChannel();

    String request = "GET " + file + " HTTP/1.1\r\n" + "User-Agent: HTTPGrab\r\n" + "Accept: text/*\r\n"
            + "Connection: close\r\n" + "Host: " + host + "\r\n" + "\r\n";

    ByteBuffer header = ByteBuffer.wrap(request.getBytes("US-ASCII"));
    channel.write(header);

    ByteBuffer buffer = ByteBuffer.allocate(8192);
    while (channel.read(buffer) != -1) {
        buffer.flip();
        localFile.write(buffer);
        buffer.clear();
    }

    localFile.close();
    channel.close();
}

From source file:com.bia.config.Main.java

public static void main(String[] args) throws Exception {
    ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring/applicationContext*.xml");

    EmployeeCassandraServiceImpl service = context.getBean(EmployeeCassandraServiceImpl.class);

    Emp emp = new Emp();
    emp.setId((new Date()).toString());
    String username = "IM-" + new Date();
    emp.setUsername(username);//from  w  w w. j a va  2 s  . co m
    emp.setJoinDate(new Date());
    emp.setStorageSize(10.0);
    emp.setContent(ByteBuffer
            .wrap(IOUtils.toByteArray(Main.class.getClassLoader().getResourceAsStream("log4j.properties"))));

    service.saveEmployee(emp);
    int count = 0;
    for (Emp e : service.findAllEmployees()) {
        System.out.println(e + String.valueOf(e.getContent()));
        System.out.println(new String(e.getContent().array()));
        count++;
    }

    System.out.println("done " + count);

    System.out.println(service.findByUsername(username));

}

From source file:Test.java

public static void main(String[] args) throws Exception {
    AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(Paths.get("/asynchronous.txt"),
            StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
    CompletionHandler<Integer, Object> handler = new CompletionHandler<Integer, Object>() {

        @Override//from  w w  w  .  j  a va  2  s. c o  m
        public void completed(Integer result, Object attachment) {
            System.out.println("Attachment: " + attachment + " " + result + " bytes written");
            System.out.println("CompletionHandler Thread ID: " + Thread.currentThread().getId());
        }

        @Override
        public void failed(Throwable e, Object attachment) {
            System.err.println("Attachment: " + attachment + " failed with:");
            e.printStackTrace();
        }
    };

    System.out.println("Main Thread ID: " + Thread.currentThread().getId());
    fileChannel.write(ByteBuffer.wrap("Sample".getBytes()), 0, "First Write", handler);
    fileChannel.write(ByteBuffer.wrap("Box".getBytes()), 0, "Second Write", handler);

}

From source file:MainClass.java

public static void main(String[] args) {
    File aFile = new File("primes.txt");
    FileInputStream inFile = null;
    try {/*from   w w w .  j a v a  2 s. c  o  m*/
        inFile = new FileInputStream(aFile);
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.err);
    }
    FileChannel inChannel = inFile.getChannel();
    try {
        ByteBuffer lengthBuf = ByteBuffer.allocate(8);
        while (true) {
            if (inChannel.read(lengthBuf) == -1) {
                break;
            }
            lengthBuf.flip();
            int strLength = (int) lengthBuf.getDouble();
            ByteBuffer buf = ByteBuffer.allocate(2 * strLength + 8);
            if (inChannel.read(buf) == -1) {
                break;
            }
            buf.flip();
            byte[] strChars = new byte[2 * strLength];
            buf.get(strChars);
            System.out.println(strLength);
            System.out.println(ByteBuffer.wrap(strChars).asCharBuffer());
            System.out.println(buf.getLong());
            lengthBuf.clear();
        }
        inFile.close();
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    File aFile = new File("primes.txt");
    FileInputStream inFile = new FileInputStream(aFile);
    FileChannel inChannel = inFile.getChannel();
    ByteBuffer buf = ByteBuffer.allocateDirect(1024);
    buf.position(buf.limit());/* w  w w.java  2  s  .co m*/
    while (true) {
        if (buf.remaining() < 8) {
            if (inChannel.read(buf.compact()) == -1) {
                break;
            }
            buf.flip();
        }
        int strLength = (int) buf.getDouble();
        if (buf.remaining() < 2 * strLength) {
            if (inChannel.read(buf.compact()) == -1) {
                break;
            }
            buf.flip();
        }
        byte[] strChars = new byte[2 * strLength];
        buf.get(strChars);
        if (buf.remaining() < 8) {
            if (inChannel.read(buf.compact()) == -1) {
                break;
            }
            buf.flip();
        }
        System.out.println(strLength);
        System.out.println(ByteBuffer.wrap(strChars).asCharBuffer());
        System.out.println(buf.getLong());
    }
    inFile.close();
}

From source file:MainClass.java

public static void main(String[] args) throws IOException {
    for (int i = 0; i < data.length; i++)
        data[i] = (byte) i;

    ServerSocketChannel server = ServerSocketChannel.open();
    server.configureBlocking(false);/*from   www. j a  v  a2 s .c  o  m*/

    server.socket().bind(new InetSocketAddress(9000));
    Selector selector = Selector.open();
    server.register(selector, SelectionKey.OP_ACCEPT);

    while (true) {
        selector.select();
        Set readyKeys = selector.selectedKeys();
        Iterator iterator = readyKeys.iterator();
        while (iterator.hasNext()) {
            SelectionKey key = (SelectionKey) iterator.next();
            iterator.remove();
            if (key.isAcceptable()) {
                SocketChannel client = server.accept();
                System.out.println("Accepted connection from " + client);
                client.configureBlocking(false);
                ByteBuffer source = ByteBuffer.wrap(data);
                SelectionKey key2 = client.register(selector, SelectionKey.OP_WRITE);
                key2.attach(source);
            } else if (key.isWritable()) {
                SocketChannel client = (SocketChannel) key.channel();
                ByteBuffer output = (ByteBuffer) key.attachment();
                if (!output.hasRemaining()) {
                    output.rewind();
                }
                client.write(output);
            }
            key.channel().close();
        }
    }
}