Example usage for java.nio ByteBuffer flip

List of usage examples for java.nio ByteBuffer flip

Introduction

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

Prototype

public final Buffer flip() 

Source Link

Document

Flips this buffer.

Usage

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 {/* ww  w  .  jav  a  2s.  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());
    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:Main.java

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

    File aFile = new File("test.txt");
    FileOutputStream outputFile = null;
    outputFile = new FileOutputStream(aFile, true);
    System.out.println("File stream created successfully.");

    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);//w w w.  j a v a 2  s. c  o  m
    }
    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());

    outChannel.write(buf);
    outputFile.close();
    System.out.println("Buffer contents written to file.");
}

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 {//from   w ww  .  ja  va 2  s .c  om
        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:GetWebPageDemo.java

public static void main(String args[]) throws Exception {
    String resource, host, file;// w ww . j a v a  2  s .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:MainClass.java

public static void main(String[] args) throws Exception {
    createFile();/*from ww w  .ja va 2  s  .  c  o  m*/

    File aFile = new File("C:/primes.bin");
    FileInputStream inFile = new FileInputStream(aFile);

    FileChannel inChannel = inFile.getChannel();

    final int PRIMESREQUIRED = 10;
    ByteBuffer buf = ByteBuffer.allocate(8 * PRIMESREQUIRED);

    long[] primes = new long[PRIMESREQUIRED];
    int index = 0; // Position for a prime in the file

    // Count of primes in the file
    final int PRIMECOUNT = (int) inChannel.size() / 8;

    // Read the number of random primes required
    for (int i = 0; i < PRIMESREQUIRED; i++) {
        index = 8 * (int) (PRIMECOUNT * Math.random());
        inChannel.read(buf, index); // Read the value
        buf.flip();
        primes[i] = buf.getLong(); // Save it in the array
        buf.clear();
    }

    for (long prime : primes) {
        System.out.printf("%12d", prime);
    }
    inFile.close(); // Close the file and the channel

}

From source file:MainClass.java

public static void main(String[] args) {
    long[] primes = new long[] { 1, 2, 3, 5, 7 };
    File aFile = new File("C:/test/primes.txt");
    FileOutputStream outputFile = null;
    try {/*from w ww.  jav  a  2s . c  o  m*/
        outputFile = new FileOutputStream(aFile);
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.err);
    }
    FileChannel file = outputFile.getChannel();
    final int BUFFERSIZE = 100;
    ByteBuffer buf = ByteBuffer.allocate(BUFFERSIZE);
    DoubleBuffer doubleBuf = buf.asDoubleBuffer();
    buf.position(8);
    CharBuffer charBuf = buf.asCharBuffer();
    for (long prime : primes) {
        String primeStr = "prime = " + prime;
        doubleBuf.put(0, (double) primeStr.length());
        charBuf.put(primeStr);
        buf.position(2 * charBuf.position() + 8);
        LongBuffer longBuf = buf.asLongBuffer();
        longBuf.put(prime);
        buf.position(buf.position() + 8);
        buf.flip();
        try {
            file.write(buf);
        } catch (IOException e) {
            e.printStackTrace(System.err);
        }
        buf.clear();
        doubleBuf.clear();
        charBuf.clear();
    }
    try {
        System.out.println("File written is " + file.size() + "bytes.");
        outputFile.close();
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
}

From source file:com.openteach.diamond.network.waverider.session.DefaultSession.java

public static void main(String[] args) {

    BlockingQueue<ByteBuffer> inputBuffer = new LinkedBlockingQueue<ByteBuffer>();
    /*for (int i = 0; i < 10; i++)
    {*//*from   w  w w  .ja v  a  2 s . c  o m*/
    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
    byteBuffer.put(makePacket().marshall());
    byteBuffer.put(makePacket().marshall());
    byteBuffer.flip();
    byte[] b = new byte[8];
    ByteBuffer halfBuf0 = ByteBuffer.allocate(8);
    byteBuffer.get(b);
    halfBuf0.put(b);
    halfBuf0.flip();
    inputBuffer.add(halfBuf0);
    inputBuffer.add(byteBuffer);
    /*}*/

    int size = 0;
    int oldSize = size;
    long length = Packet.getHeaderSize();
    ByteBuffer buffer = ByteBuffer.allocate(NetWorkConstants.DEFAULT_NETWORK_BUFFER_SIZE);
    ByteBuffer currentBuffer = null;

    while (size < length) {
        currentBuffer = inputBuffer.peek();
        oldSize = size;
        int position = currentBuffer.position();
        size += currentBuffer.remaining();
        buffer.put(currentBuffer);
        if (size >= Packet.getHeaderSize()) {
            length = buffer.getLong(Packet.getLengthPosition());
        }

        if (size <= length) {
            inputBuffer.remove();
        } else {
            currentBuffer.position(position);
            buffer.position(buffer.position() - currentBuffer.remaining());
            byte[] buf = new byte[(int) (length - oldSize)];
            currentBuffer.get(buf);
            buffer.put(buf);
        }
    }

    // buffer.position(0);
    buffer.flip();
    Packet packet = Packet.unmarshall(buffer);

    Command command = CommandFactory.createCommand(packet.getType(), packet.getPayLoad());

    String str = new String(command.getPayLoad().array());

    System.out.println(str);

}

From source file:UDPTimeServer.java

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

    int port = 37;

    ByteBuffer in = ByteBuffer.allocate(8192);
    ByteBuffer out = ByteBuffer.allocate(8);
    out.order(ByteOrder.BIG_ENDIAN);
    SocketAddress address = new InetSocketAddress(port);
    DatagramChannel channel = DatagramChannel.open();
    DatagramSocket socket = channel.socket();
    socket.bind(address);//from w  w  w.j  ava 2 s .co  m
    System.err.println("bound to " + address);
    while (true) {
        try {
            in.clear();
            SocketAddress client = channel.receive(in);
            System.err.println(client);
            long secondsSince1970 = System.currentTimeMillis();
            out.clear();
            out.putLong(secondsSince1970);
            out.flip();

            out.position(4);
            channel.send(out, client);
        } catch (Exception ex) {
            System.err.println(ex);
        }
    }
}

From source file:org.apache.hadoop.hdfs.hoss.db.FileBlockStore.java

public static void main(String[] args) {
    final int BLOCK_SIZE = 64;
    final int TOTAL = 10000000;
    final FileBlockStore fbs = new FileBlockStore("./data/block", BLOCK_SIZE, false);
    fbs.delete();/*from  w  ww.  j  av a  2s  .c o m*/
    // fbs.enableMmap(); // Test MMAPED?
    fbs.open();
    long start = System.currentTimeMillis();
    for (int i = 0; i < TOTAL; i++) {
        final WriteBuffer wbuf = fbs.set(i);
        final ByteBuffer buf = wbuf.buf();
        StringSerializer.fromStringToBuffer(buf, "hehe" + i);
        buf.putLong(i);
        buf.flip();
        wbuf.save();
    }
    //
    fbs.sync();
    System.out.println("write time: " + (System.currentTimeMillis() - start) / 1000);
    start = System.currentTimeMillis();
    for (int j = 0; j < TOTAL; j++) {
        final ByteBuffer buf = fbs.get(j);
        if (buf == null) {
            System.out.println("Error trying read block " + j + " blocks=" + fbs.numBlocks());
            break;
        }
        StringSerializer.fromBufferToString(buf);
        buf.getLong();
        //System.out.print("\t" + hehe + "\t" + offset);
    }
    System.out.println("read time: " + (System.currentTimeMillis() - start) / 1000);
    fbs.close();

}

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   www  .j a  va 2  s . co 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) {
        }
    }
}