[英]Assigning to a byte array in Java
我有一個我想要分配的字節數組,如下所示:
(byte)string.length()
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());
雖然像其他人建議的那樣使用像ByteArrayOutputStream
或ByteBuffer
這樣的東西可能是一種更清潔的方法,從長遠來看對你來說會更好:-)
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.