簡體   English   中英

在Java中分配給字節數組

[英]Assigning to a byte array in Java

我有一個我想要分配的字節數組,如下所示:

  • 第一個字節指定字符串的長度: (byte)string.length()
  • 2nd - 最后一個字節包含string.getBytes()字符串數據

除了使用for循環之外,還有一種使用來自兩個不同變量的字節初始化字節數組的快捷方法嗎?

您可以使用System.arrayCopy()來復制您的字節:

String x = "xx";
byte[] out = new byte[x.getBytes().length()+1];
out[0] = (byte) (0xFF & x.getBytes().length());
System.arraycopy(x.getBytes(), 0, out, 1, x.length());

雖然像其他人建議的那樣使用像ByteArrayOutputStreamByteBuffer這樣的東西可能是一種更清潔的方法,從長遠來看對你來說會更好:-)

ByteBuffer怎么樣?

示例:

    ByteBuffer bb = ByteBuffer.allocate(string.getBytes().length +1 );
    bb.put((byte) string.length());
    bb.put(string.getBytes());

雖然ByteBuffer通常是構建字節數組的最佳方法,但考慮到OP的目標,我認為以下內容將更加健壯:

public static void main(String[] argv)
throws Exception
{
   String s = "any string up to 64k long";

   ByteArrayOutputStream bos = new ByteArrayOutputStream();
   DataOutputStream out = new DataOutputStream(bos);
   out.writeUTF(s);
   out.close();

   byte[] bytes = bos.toByteArray();

   ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
   DataInputStream in = new DataInputStream(bis);

   String s2 = in.readUTF();
}

ByteArrayOutputStream怎么樣?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM