Java自定义FilterInputStream如何重写read(byte[])复用单字节read()逻辑
自定义FilterInputStream重写read(byte[])方法实现方案
你只需要复用已经重写完成的无参read()方法做逐字节读取,就能保证替换逻辑完全统一,不需要重复编写65转194的判断规则。
需要注意read(byte[] b)方法需要符合InputStream的接口约定:返回实际读取的字节数,流末尾返回-1,同时兼容空数组、下标越界等异常校验。
另外建议同步重写三参数的read(byte[] b, int off, int len)方法,因为FilterInputStream的默认实现中read(byte[] b)本质是调用read(b, 0, b.length),仅重写单参数方法会导致三参数调用时逻辑不生效。
完整实现代码
public class CustomInput extends FilterInputStream{ protected CustomInput(InputStream in) { super(in); } @Override public int read() throws IOException { int y=super.read(); if(y==65) { return 194; } else { return y; } } @Override public int read(byte[] b) throws IOException{ // 直接复用三参数重载方法 return read(b, 0, b.length); } @Override public int read(byte[] b, int off, int len) throws IOException { // 标准参数校验,符合InputStream接口规范 if (b == null) { throw new NullPointerException(); } if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException(); } if (len == 0) { return 0; } // 读取第一个字节判断是否到达流末尾 int firstByte = read(); if (firstByte == -1) { return -1; } b[off] = (byte) firstByte; int readCount = 1; // 循环读取剩余字节,直到读够指定长度或到达流末尾 for (; readCount < len; readCount++) { int currentByte = read(); if (currentByte == -1) { break; } b[off + readCount] = (byte) currentByte; } return readCount; } }
注意事项
- 所有字节读取逻辑都复用了你已经实现的无参
read()方法,后续如果要修改替换规则,只需要修改无参read()即可,三处方法逻辑自动同步 - Java中byte是带符号8位类型,194存入byte数组后会显示为-62,读取时将其转成int(需要和0xFF做与运算消除符号位)即可得到194的正确数值,符合InputStream的使用规范
内容的提问来源于stack exchange,提问作者Eric Movsessian
相关产品推荐
相关产品推荐

