Created
January 9, 2014 06:32
-
-
Save mviitanen/8330263 to your computer and use it in GitHub Desktop.
Java ByteBuffer demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.nio.ByteBuffer; | |
public class BufferTest { | |
private ByteBuffer buffer; | |
public BufferTest(){ | |
buffer = ByteBuffer.allocate(20); | |
} | |
public void runTest(){ | |
System.out.println("Running test"); | |
System.out.println("\nWrite 5 characters, flip, read until they are consumed (5 characters), then compact"); | |
dumpBuffer(buffer.duplicate()); | |
buffer.put("hello".getBytes()); | |
System.out.println("Put \"hello\""); | |
dumpBuffer(buffer.duplicate()); | |
buffer.flip(); | |
System.out.println("Flipped"); | |
dumpBuffer(buffer.duplicate()); | |
while(buffer.hasRemaining()){ | |
System.out.print( ((char)buffer.get()) + " " ); | |
} | |
System.out.println(); | |
dumpBuffer(buffer.duplicate()); | |
buffer.compact(); | |
System.out.println("Compacted"); | |
dumpBuffer(buffer.duplicate()); | |
System.out.println("\nWrite 20 characters, flip, read 5 characters, then compact"); | |
buffer.put("11111222223333344444".getBytes()); | |
System.out.println("Put \"11111222223333344444\""); | |
dumpBuffer(buffer.duplicate()); | |
buffer.flip(); | |
System.out.println("Flipped"); | |
dumpBuffer(buffer.duplicate()); | |
int i = 0; | |
while(i++ < 5 && buffer.hasRemaining()){ | |
System.out.print(((char)buffer.get()) +" " ); | |
} | |
System.out.println(); | |
dumpBuffer(buffer.duplicate()); | |
buffer.compact(); | |
System.out.println("Compacted"); | |
dumpBuffer(buffer.duplicate()); | |
System.out.println("\nWrite 5 characters, flip, read until they are consumed (20 characters), then compact"); | |
buffer.put("55555".getBytes()); | |
System.out.println("Put \"55555\""); | |
dumpBuffer(buffer.duplicate()); | |
buffer.flip(); | |
System.out.println("Flipped"); | |
dumpBuffer(buffer.duplicate()); | |
while(buffer.hasRemaining()){ | |
System.out.print(((char)buffer.get()) +" " ); | |
} | |
System.out.println(); | |
dumpBuffer(buffer.duplicate()); | |
buffer.compact(); | |
System.out.println("Compacted"); | |
dumpBuffer(buffer.duplicate()); | |
System.out.println("Done running test"); | |
} | |
private void dumpBuffer(ByteBuffer b){ | |
System.out.println("position: " + b.position() +" limit:" + b.limit() + " has more:" + b.hasRemaining() ); | |
} | |
public static void main(String[] args){ | |
BufferTest test = new BufferTest(); | |
test.runTest(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment