讀取 java.nio.ByteBuffer 中的字符串(String) 寫入方式flash.utils.ByteArray.writeUTF


通過研究ByteArray的寫入格式以及方法說明,可以發現writeUTF是先使用2位寫入字符串的長度,然后在其后寫入字符串編碼。

 ByteArray.writeUTF

flash.utils.ByteArray.writeUTF(value:String):void 

UTF-8 字符串寫入字節流。先寫入以字節表示的 UTF-8 字符串長度(作為 16 位整數),然后寫入表示字符串字符的字節。

 

那么在java后端就可以根據規則讀取寫入的字符串了。 

public static String getString(ByteBuffer packDataBuff)
{
if (packDataBuff.remaining() <= 0)
return "";
byte[] lenb = new byte[2];
lenb[1] = packDataBuff.get();
lenb[0] = packDataBuff.get();
int len = Integer.parseInt(Util.bytes2HexString(lenb), 16);
byte[] d = new byte[len];
packDataBuff.get(d, 0, len);
return new String(d, Charset.forName("UTF-8"));
}

 

public static String bytes2HexString(byte[] b)
{
String ret = "";
for (int i = 0; i < b.length; i++)
{
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1)
{
hex = '0' + hex;
}
ret += hex;
}
return ret;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM