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

public static void main(String[] args) throws Exception {
    AsynchronousSocketChannel channel = AsynchronousSocketChannel.open();
    SocketAddress serverAddr = new InetSocketAddress("localhost", 8989);
    Future<Void> result = channel.connect(serverAddr);
    result.get();/*from  www  . j  a  v  a  2s  .  c o m*/
    System.out.println("Connected");
    Attachment attach = new Attachment();
    attach.channel = channel;
    attach.buffer = ByteBuffer.allocate(2048);
    attach.isRead = false;
    attach.mainThread = Thread.currentThread();

    Charset cs = Charset.forName("UTF-8");
    String msg = "Hello";
    byte[] data = msg.getBytes(cs);
    attach.buffer.put(data);
    attach.buffer.flip();

    ReadWriteHandler readWriteHandler = new ReadWriteHandler();
    channel.write(attach.buffer, attach, readWriteHandler);
    attach.mainThread.join();
}

From source file:MainClass.java

public static void main(String[] args) {
    String phrase = new String("text \n");
    String dirname = "C:/test";
    String filename = "charData.txt";
    File dir = new File(dirname);
    File aFile = new File(dir, filename);
    FileOutputStream outputFile = null;
    try {/*from w ww  .j a  v  a  2s .  c o  m*/
        outputFile = new FileOutputStream(aFile, true);
        System.out.println("File stream created successfully.");
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.err);
    }
    FileChannel outChannel = outputFile.getChannel();
    ByteBuffer buf = ByteBuffer.allocate(1024);
    System.out.println("New buffer:           position = " + buf.position() + "\tLimit = " + buf.limit()
            + "\tcapacity = " + buf.capacity());
    for (char ch : phrase.toCharArray()) {
        buf.putChar(ch);
    }
    System.out.println("Buffer after loading: position = " + buf.position() + "\tLimit = " + buf.limit()
            + "\tcapacity = " + buf.capacity());
    buf.flip();
    System.out.println("Buffer after flip:   position = " + buf.position() + "\tLimit = " + buf.limit()
            + "\tcapacity = " + buf.capacity());
    try {
        outChannel.write(buf);
        outputFile.close();
        System.out.println("Buffer contents written to file.");
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
}

From source file:MainClass.java

public static void main(String[] args) {
    String[] phrases = { "A", "B 1", "C 1.3" };
    String dirname = "C:/test";
    String filename = "Phrases.txt";
    File dir = new File(dirname);
    File aFile = new File(dir, filename);
    FileOutputStream outputFile = null;
    try {// ww  w.java2s  . co  m
        outputFile = new FileOutputStream(aFile, true);
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.err);
    }
    FileChannel outChannel = outputFile.getChannel();
    ByteBuffer buf = ByteBuffer.allocate(1024);
    System.out.println(buf.position());
    System.out.println(buf.limit());
    System.out.println(buf.capacity());
    CharBuffer charBuf = buf.asCharBuffer();
    System.out.println(charBuf.position());
    System.out.println(charBuf.limit());
    System.out.println(charBuf.capacity());
    Formatter formatter = new Formatter(charBuf);
    int number = 0;
    for (String phrase : phrases) {
        formatter.format("%n %s", ++number, phrase);
        System.out.println(charBuf.position());
        System.out.println(charBuf.limit());
        System.out.println(charBuf.capacity());
        charBuf.flip();
        System.out.println(charBuf.position());
        System.out.println(charBuf.limit());
        System.out.println(charBuf.length());
        buf.limit(2 * charBuf.length()); // Set byte buffer limit
        System.out.println(buf.position());
        System.out.println(buf.limit());
        System.out.println(buf.remaining());
        try {
            outChannel.write(buf);
            buf.clear();
            charBuf.clear();
        } catch (IOException e) {
            e.printStackTrace(System.err);
        }
    }
    try {
        outputFile.close();
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
}

From source file:MainClass.java

public static void main(String[] args) {
    int count = 100;

    long[] numbers = new long[count];

    for (int i = 0; i < numbers.length; i++) {
        numbers[i] = i;//from www  .j  a va  2 s .c o  m

    }
    File aFile = new File("data.bin");
    FileOutputStream outputFile = null;
    try {
        outputFile = new FileOutputStream(aFile);
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    }
    FileChannel file = outputFile.getChannel();
    final int BUFFERSIZE = 100;
    ByteBuffer buf = ByteBuffer.allocate(BUFFERSIZE);
    LongBuffer longBuf = buf.asLongBuffer();

    int numberWritten = 0;

    while (numberWritten < numbers.length) {
        longBuf.put(numbers, numberWritten, min(longBuf.capacity(), numbers.length - numberWritten));
        buf.limit(8 * longBuf.position());
        try {
            file.write(buf);
            numberWritten += longBuf.position();
        } catch (IOException e) {
            e.printStackTrace(System.err);
            System.exit(1);
        }
        longBuf.clear();
        buf.clear();
    }

    try {
        System.out.println("File written is " + file.size() + " bytes.");
        outputFile.close();
    } catch (IOException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    }
}

From source file:GetChannel.java

public static void main(String[] args) throws Exception {
    // Write a file:
    FileChannel fc = new FileOutputStream("data.txt").getChannel();
    fc.write(ByteBuffer.wrap("Some text ".getBytes()));
    fc.close();/*from w ww.ja  v  a  2s .c  om*/
    // Add to the end of the file:
    fc = new RandomAccessFile("data.txt", "rw").getChannel();
    fc.position(fc.size()); // Move to the end
    fc.write(ByteBuffer.wrap("Some more".getBytes()));
    fc.close();
    // Read the file:
    fc = new FileInputStream("data.txt").getChannel();
    ByteBuffer buff = ByteBuffer.allocate(BSIZE);
    fc.read(buff);
    buff.flip();
    while (buff.hasRemaining())
        System.out.print((char) buff.get());
}

From source file:MainClass.java

public static void main(String[] args) {
    String phrase = new String("www.java2s.com\n");

    File aFile = new File("test.txt");
    FileOutputStream outputFile = null;
    try {/*  w w  w.  j  ava2  s .  co m*/
        outputFile = new FileOutputStream(aFile, true);
        System.out.println("File stream created successfully.");
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.err);
    }

    FileChannel outChannel = outputFile.getChannel();

    ByteBuffer buf = ByteBuffer.allocate(1024);
    System.out.println("New buffer:           position = " + buf.position() + "\tLimit = " + buf.limit()
            + "\tcapacity = " + buf.capacity());

    // Load the data into the buffer
    for (char ch : phrase.toCharArray()) {
        buf.putChar(ch);
    }
    System.out.println("Buffer after loading: position = " + buf.position() + "\tLimit = " + buf.limit()
            + "\tcapacity = " + buf.capacity());
    buf.flip();
    System.out.println("Buffer after flip:    position = " + buf.position() + "\tLimit = " + buf.limit()
            + "\tcapacity = " + buf.capacity());

    try {
        outChannel.write(buf);
        outputFile.close();
        System.out.println("Buffer contents written to file.");
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
}

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();//from  ww  w  .  ja va 2s.c o m
    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.moscona.dataSpace.debug.ByteBufferTest.java

public static void main(String[] args) {
    ByteBuffer bytes = ByteBuffer.allocate(40);
    print("after allocation", bytes);
    byte[] byteArray = bytes.array();
    for (int i = 0; i < byteArray.length; i++) {
        byteArray[i] = 1;/*from  www .  ja  v  a  2 s.  c o  m*/
    }
    print("after filling with 1s", bytes);
    IntBuffer ints = bytes.asIntBuffer();
    System.out.println("ints has array: " + ints.hasArray());
    int[] array = ints.array();
    for (int i = 0; i < array.length; i++) {
        array[i] = 100 + i;
    }
    print("after filling ints array", bytes);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    MembershipKey key = null;//from  w w w. ja  va2  s .  com
    DatagramChannel client = DatagramChannel.open(StandardProtocolFamily.INET);

    NetworkInterface interf = NetworkInterface.getByName(MULTICAST_INTERFACE_NAME);
    client.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    client.bind(new InetSocketAddress(MULTICAST_PORT));
    client.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);

    InetAddress group = InetAddress.getByName(MULTICAST_IP);
    key = client.join(group, interf);

    System.out.println("Joined the   multicast  group:" + key);
    System.out.println("Waiting for a  message  from  the" + "  multicast group....");

    ByteBuffer buffer = ByteBuffer.allocate(1048);
    client.receive(buffer);
    buffer.flip();
    int limits = buffer.limit();
    byte bytes[] = new byte[limits];
    buffer.get(bytes, 0, limits);
    String msg = new String(bytes);

    System.out.format("Multicast Message:%s%n", msg);
    key.drop();
}

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>() {
        public synchronized void completed(Integer result, ByteBuffer attachment) {
            for (int i = 0; i < attachment.limit(); i++) {
                System.out.print((char) attachment.get(i));
            }// w  ww  .ja  va  2s .  c  o m
        }

        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.println((char) byteBuffer.get(i));
        }
    }
}