Skip to content

Instantly share code, notes, and snippets.

@kdlan
Created March 12, 2015 08:03
Show Gist options
  • Select an option

  • Save kdlan/1650d67e2bb7063f1a45 to your computer and use it in GitHub Desktop.

Select an option

Save kdlan/1650d67e2bb7063f1a45 to your computer and use it in GitHub Desktop.
ByteBufferTest
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