Created
March 12, 2015 08:03
-
-
Save kdlan/1650d67e2bb7063f1a45 to your computer and use it in GitHub Desktop.
ByteBufferTest
This file contains hidden or 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 static org.junit.Assert.*; | |
| import java.nio.ByteBuffer; | |
| import org.junit.Test; | |
| public class ByteBufferTest { | |
| @Test | |
| public void test1() { | |
| ByteBuffer bf = ByteBuffer.allocate(1024); | |
| bf.putInt(1); | |
| bf.put("123".getBytes()); | |
| bf.put((byte) 0); | |
| bf.putInt(2); | |
| bf.flip(); | |
| assertEquals(1, bf.getInt()); | |
| byte[] result = new byte["123".getBytes().length]; | |
| bf.get(result); | |
| assertArrayEquals("123".getBytes(), result); | |
| assertEquals((byte) 0, bf.get()); | |
| // int 2 is remain in the buffer | |
| assertTrue(bf.hasRemaining()); | |
| bf=bf.compact(); | |
| assertEquals(Integer.BYTES,bf.position()); | |
| bf.flip(); | |
| assertEquals(0,bf.position()); | |
| assertTrue(bf.hasRemaining()); | |
| //read 2 | |
| assertEquals(2,bf.getInt()); | |
| assertFalse(bf.hasRemaining()); | |
| bf.clear(); | |
| } | |
| @Test | |
| public void test2() { | |
| ByteBuffer bf = ByteBuffer.allocate(1024); | |
| bf.putInt(1); | |
| bf.put("123".getBytes()); | |
| bf.put((byte) 0); | |
| bf.putInt(2); | |
| bf.flip(); | |
| assertEquals(1, bf.getInt()); | |
| byte[] result = new byte["123".getBytes().length]; | |
| bf.get(result); | |
| assertArrayEquals("123".getBytes(), result); | |
| assertEquals((byte) 0, bf.get()); | |
| //rewind position to 0; | |
| bf.rewind(); | |
| assertEquals(1, bf.getInt()); | |
| result = new byte["123".getBytes().length]; | |
| bf.get(result); | |
| assertArrayEquals("123".getBytes(), result); | |
| assertEquals((byte) 0, bf.get()); | |
| assertEquals(2,bf.getInt()); | |
| } | |
| @Test | |
| public void test3() { | |
| ByteBuffer bf = ByteBuffer.allocate(1024); | |
| bf.putInt(1); | |
| bf.put("123".getBytes()); | |
| bf.put((byte) 0); | |
| bf.putInt(2); | |
| bf.flip(); | |
| assertEquals(1, bf.getInt()); | |
| byte[] result = new byte["123".getBytes().length]; | |
| bf.get(result); | |
| assertArrayEquals("123".getBytes(), result); | |
| assertEquals((byte) 0, bf.get()); | |
| bf.mark(); | |
| assertEquals(2,bf.getInt()); | |
| bf.reset(); | |
| assertEquals(2,bf.getInt()); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment