Using Buffers : Buffering « File Input Output « Java






Using Buffers

Using Buffers
     
// : c12:UsingBuffers.java
// From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
// www.BruceEckel.com. See copyright notice in CopyRight.txt.

import java.nio.ByteBuffer;
import java.nio.CharBuffer;

public class UsingBuffers {
  private static void symmetricScramble(CharBuffer buffer) {
    while (buffer.hasRemaining()) {
      buffer.mark();
      char c1 = buffer.get();
      char c2 = buffer.get();
      buffer.reset();
      buffer.put(c2).put(c1);
    }
  }

  public static void main(String[] args) {
    char[] data = "UsingBuffers".toCharArray();
    ByteBuffer bb = ByteBuffer.allocate(data.length * 2);
    CharBuffer cb = bb.asCharBuffer();
    cb.put(data);
    System.out.println(cb.rewind());
    symmetricScramble(cb);
    System.out.println(cb.rewind());
    symmetricScramble(cb);
    System.out.println(cb.rewind());

  }
} ///:~



           
         
    
    
    
    
  








Related examples in the same category

1.Endian differences and data storageEndian differences and data storage
2.View BuffersView Buffers
3.Output BufferingOutput Buffering
4.Getting different representations from a ByteBufferGetting different representations from a ByteBuffer
5.Manipulating ints in a ByteBuffer with an IntBufferManipulating ints in a ByteBuffer with an IntBuffer
6.Circular Byte Buffer
7.Circular Char Buffer from http://ostermiller.org
8.Buffered copying
9.Byte Buffer
10.Circular Char Buffer
11.Char Buffer
12.Caching InputStream
13.Caching OutputStream
14.ByteBuffer FloatBuffer demo