当前位置:   article > 正文

byte数组 合并 与 截取(java)_截取byte数组

截取byte数组

 合并数组

  1.         /**
  2. * 合并byte[]数组 (不改变原数组)
  3. * @param byte_1
  4. * @param byte_2
  5. * @return 合并后的数组
  6. */
  7.     public byte[] byteMerger(byte[] byte_1, byte[] byte_2){
  8. byte[] byte_3 = new byte[byte_1.length+byte_2.length];
  9. System.arraycopy(byte_1, 0, byte_3, 0, byte_1.length);
  10. System.arraycopy(byte_2, 0, byte_3, byte_1.length, byte_2.length);
  11. return byte_3;
  12. }

截取数组

  1. /**
  2. * 截取byte数组 不改变原数组
  3. * @param b 原数组
  4. * @param off 偏差值(索引)
  5. * @param length 长度
  6. * @return 截取后的数组
  7. */
  8. public byte[] subByte(byte[] b,int off,int length){
  9. byte[] b1 = new byte[length];
  10. System.arraycopy(b, off, b1, 0, length);
  11. return b1;
  12. }

采用的JAVA_API:

  1. System.arraycopy(src, srcPos, dest, destPos, length)
  2. 参数解析:
  3. src:byte源数组
  4. srcPos:截取源byte数组起始位置(0位置有效)
  5. dest,:byte目的数组(截取后存放的数组)
  6. destPos:截取后存放的数组起始位置(0位置有效)
  7. length:截取的数据长度

对于很多人上边的方法已经足够使用了,但是对于多个字节数组合并与截取就稍微显得相形见绌!java官方提供了一种操作字节数组的方法——内存流(字节数组流)ByteArrayInputStream、ByteArrayOutputStream,值得一提的是这个流内部采用的也是System.arraycopy该API,所以不是很复杂的功能的话,采用上方的方法就好

ByteArrayOutputStream——byte数组合并

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

ByteArrayInputStream——byte数组截取

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

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/427527
推荐阅读
相关标签
  

闽ICP备14008679号