java - Java中如何解决字节填充问题?

标签 java io binaryfiles

我正在读取Java中的二进制文件,该文件在保存时是字节填充的,因此读取时必须反转操作。填充在于在 FF 字节后添加一个额外的零字节。读取时必须丢弃该零字节。我正在使用 DataInputStream 来读取文件,尽管这应该不会有太大区别,看看我如何仅使用“原始”读取数组函数来读取该文件的该部分程序。

无论如何,这是我到目前为止所得到的:

public static byte[] unstuff(byte[] stuffed) {
    int bytesToSkip = 0;
    for(int i=0;i<stuffed.length - 1;++i) {
        if(stuffed[i] == 0xFF && stuffed[i+1] == 0) {
            ++bytesToSkip;
        }
    }
    if(bytesToSkip == 0) return stuffed;

    byte unstuffed[] = new byte[stuffed.length - bytesToSkip];
    int j=0;
    for(int i=0;i<stuffed.length - 1;++i) {
        if(stuffed[i] == 0xFF && stuffed[i+1] == 0) {
            ++i;
            continue;
        }
        else {
            unstuffed[j] = stuffed[i];
            ++j;
        }
    }
    return unstuffed;
}

基本上,该函数计算要跳过的字节数,然后分配一个比原始填充数组短该字节数的数组,并将它们复制过来,跳过不需要的零字节。

问题是:有没有其他方法可以做到这一点,也许更灵活、更高效、更直接?将字节放入另一个容器中然后删除它们而不是复制整个数组会更好吗?

最佳答案

您可以将其作为 InputStream 本身的包装器:

new DataInputStream(new FilterInputStream(stream)) {
  int buf = -1;

  public int read() {
    if (buf != -1) {
      int result = buf;
      buf = -1;
      return result;
    } else {
      int b = super.read();
      if (b == 0xFF) {
        super.skip(1); // skip the 0 byte
      }
      return b;
    }
  }

  public int read(byte[] bytes, int off, int len) {
    int dst = 0;
    while (dst == 0) {
      int readBytes = super.read(bytes, off, len);
      if (readBytes == -1) return -1;
      int dst = 0;
      for (int i = 0; i < readBytes; i++) {
        bytes[off + dst] = bytes[off + i];
        if (bytes[off + i] == (byte) 0xFF) {
          i++; // skip the 0 byte afterwards
        }
      }
    }
    return dst;
  }
}

关于java - Java中如何解决字节填充问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13440775/

相关文章:

python - 将二进制数据插入pymongo中的Mongo字段

安卓 2.2 : best way to read small blocks of binary data from big files?

java - 如何获取 Multipart 文件的真实扩展类型

Java:检测服务中注入(inject)过多依赖项

c - 将数百万次写入文件会破坏我的硬盘吗?

java - 应对流 - nio 的 channel 与 io

Java 显示正确 错误

java - Java 中 System.load() 和 System.loadLibrary 的区别

linux - 基于 Bash 中的行内容加速大文本文件的分离

c++ - 无法将大的无符号整数正确写入二进制文件 - C++