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

时间:2022-07-27
本文章向大家介绍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));
  }

以上就是本文的全部内容,希望对大家的学习有所帮助。