Java 中为字节数组赋值的方法有 6 种:直接赋值使用 Arrays.fill() 方法从另一个数组复制使用流从字符串转换使用缓冲区

Java 中为字节数组赋值的方法
在 Java 中,您可以使用以下方法为字节数组赋值:
1. 直接赋值
<code class="java">byte[] byteArray = {1, 2, 3, 4, 5};</code>2. 使用 Arrays.fill() 方法
立即学习“Java免费学习笔记(深入)”;
<code class="java">byte[] byteArray = new byte[5]; Arrays.fill(byteArray, (byte) 10); // 用 10 填充整个数组</code>
3. 从另一个数组复制
<code class="java">byte[] byteArray1 = {1, 2, 3, 4, 5};
byte[] byteArray2 = new byte[byteArray1.length];
System.arraycopy(byteArray1, 0, byteArray2, 0, byteArray1.length);</code>4. 使用流
<code class="java">ByteArrayInputStream bais = new ByteArrayInputStream(new byte[]{1, 2, 3, 4, 5});
byte[] byteArray = bais.readAllBytes();</code>5. 从字符串转换
<code class="java">String str = "Hello World"; byte[] byteArray = str.getBytes(); // 使用默认字符集 byte[] byteArrayWithCharset = str.getBytes(StandardCharsets.UTF_8); // 使用指定字符集</code>
6. 使用缓冲区
<code class="java">ByteBuffer byteBuffer = ByteBuffer.allocate(5); byteBuffer.put(1); byteBuffer.put(2); byteBuffer.put(3); byteBuffer.put(4); byteBuffer.put(5); byte[] byteArray = byteBuffer.array();</code>
以上就是java怎么给byte数组赋值的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号