Data { public String getString() { int length = getUnsignedInt(); if (pointer + length > data.length) { throw new IndexOutOfBoundsException("Not enough data"); } if (length == 0) { return ""; } if (length == -1) { return null; } byte[] bytes = new byte[length]; for (int i = 0; i < length; i++) { bytes[i] = (byte) getByte(); } String ret = new String(bytes); try { ret = new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { } return ret; } Data(byte[] data); int getUnsignedInt(); int getByte(); char getChar(); long getLongInteger(); String getString(); byte[] getBuffer(); String getPointer(); long getTime(); Hashtable getHashtable(); Hdata getHdata(); Info getInfo(); Infolist getInfolist(); Array getArray(); RelayObject getObject(); byte[] getByteArray(); boolean empty();  }
@Test public void testGetString() throws UnsupportedEncodingException { String testCases[] = new String[] { "Hello World", "some long message", "another message nothing special about it at all", "Test UTF-8 support from issue #1. Norwegian characters æ, ø and å.", "¥ · £ · € · $ · ¢ · ₡ · ₢ · ₣ · ₤ · ₥ · ₦ · ₧ · ₨ · ₩ · ₪ · ₫ · ₭ · ₮ · ₯ · ₹", "" }; for(int i=0;i<testCases.length; i++) { String o = testCases[i]; ByteBuffer bb = ByteBuffer.allocate(300); bb.order(ByteOrder.BIG_ENDIAN); byte[] t = o.getBytes("UTF-8"); bb.putInt(t.length); bb.put(t); Data d = new Data(bb.array()); String s = d.getString(); assertEquals(o, s); } }
@Test public void testGetStringNull() { ByteBuffer bb = ByteBuffer.allocate(6); bb.order(ByteOrder.BIG_ENDIAN); bb.putInt(-1); Data d = new Data(bb.array()); String s = d.getString(); assertEquals(null, s); }
@Test(expected = IndexOutOfBoundsException.class) public void testGetStringException() { ByteBuffer bb = ByteBuffer.allocate(4); bb.order(ByteOrder.BIG_ENDIAN); bb.putInt(bb.capacity()); Data d = new Data(bb.array()); d.getString(); }