软件编程
位置:首页>> 软件编程>> java编程>> Java byte数组操纵方式代码实例解析

Java byte数组操纵方式代码实例解析

作者:Mars.wang  发布时间:2022-02-18 16:54:12 

标签:Java,byte,数组

字节数组的关键在于它为存储在该部分内存中的每个8位值提供索引(快速),精确的原始访问,并且您可以对这些字节进行操作以控制每个位。 坏处是计算机只将每个条目视为一个独立的8位数 - 这可能是你的程序正在处理的,或者你可能更喜欢一些强大的数据类型,如跟踪自己的长度和增长的字符串 根据需要,或者一个浮点数,让你存储说3.14而不考虑按位表示。 作为数据类型,在长数组的开头附近插入或移除数据是低效的,因为需要对所有后续元素进行混洗以填充或填充创建/需要的间隙。

java官方提供了一种操作字节数组的方法——内存流(字节数组流)ByteArrayInputStream、ByteArrayOutputStream

ByteArrayOutputStream——byte数组合并


/**
 * 将所有的字节数组全部写入内存中,之后将其转化为字节数组
 */
 public static void main(String[] args) throws IOException {
   String str1 = "132";
   String str2 = "asd";
   ByteArrayOutputStream os = new ByteArrayOutputStream();
   os.write(str1.getBytes());
   os.write(str2.getBytes());
   byte[] byteArray = os.toByteArray();
   System.out.println(new String(byteArray));
 }

ByteArrayInputStream——byte数组截取


/**
 *  从内存中读取字节数组
 */
 public static void main(String[] args) throws IOException {
   String str1 = "132asd";
   byte[] b = new byte[3];
   ByteArrayInputStream in = new ByteArrayInputStream(str1.getBytes());
   in.read(b);
   System.out.println(new String(b));
   in.read(b);
   System.out.println(new String(b));
 }

来源:https://www.cnblogs.com/wangbin2188/p/11512192.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com