保存到二进制文件

时间:2012-11-09 15:31:13

标签: java file binary

我想使用java将数据保存到二进制文件中。例如,我有数字101,在我的程序中,输出文件有4个字节。如何在输出文件中仅保存三位(101)的数字? 我的程序看起来像这样:

public static void main(String args[]) throws FileNotFoundException, IOException {
    int i = 101;
    DataOutputStream os = new DataOutputStream(new FileOutputStream("file"));
    os.writeInt(i);
    os.close();
}

我找到了类似的东西:http://www.developer.nokia.com/Community/Wiki/Bit_Input/Output_Stream_utility_classes_for_efficient_data_transfer

3 个答案:

答案 0 :(得分:2)

您不能将少于一个字节写入文件。如果要编写二进制数101,请执行int i = 5并使用os.write(i)代替。这将写入一个字节:0000 0101。

答案 1 :(得分:0)

首先,你不能只向文件写3位,内存在特定值(8,16,32,64甚至128位,这是编译器/平台特定的)对齐。如果你写的尺寸小于它,它们将被扩展以匹配对齐。

其次,用二进制写的十进制数101是0b01100101。二进制数0b00000101,为十进制数。

第三,这些数字现在只有1个字节(8位)长,因此您可以使用char而不是int。

最后但并非最不重要的是,要编写非整数,请使用os.write()

为了达到你想要的效果,首先要检查你是否要写0b01100101或0b00000101。将int更改为char和相应的数字(您可以在Java中编写0b01100101)。并使用os.write()

答案 2 :(得分:0)

一个非常天真的实现,我希望它可以帮助你掌握这个想法。也未经测试,可能包含一个错误等...

class BitArray {
  // public fields for example code, in real code encapsulate
  public int bits=0; // actual count of stored bits
  public byte[] buf=new byte[1];

  private void doubleBuf() {
    byte [] tmp = new byte[buf.length * 2];
    System.arraycopy(buf, 0, tmp, 0, buf.length);
    buf = tmp;
  }

  private int arrayIndex(int bitNum) {
    return bitNum / 8;
  }

  private int bitNumInArray(int bitNum) {
    return bitNum & 7; // change to change bit order in buf's bytes
  }

  // returns how many elements of buf are actually in use, for saving etc.
  // note that last element usually contains unused bits.
  public int getUsedArrayElements() {
    return arrayIndex(this.bits-1) + 1;
  }

  // bitvalue is 0 for 0, non-0 for 1
  public void setBit(byte bitValue, int bitNum) { 
    if (bitNum >= this.bits || bitNum < 0) throw new InvalidArgumentException();
    if (bitValue == 0) this.buf[arrayIndex(bitNum)] &= ~((byte)1 << bitNumInArray(bitNum));
    else this.buf[arrayIndex(bitNum)] |= (byte)1 << bitNumInArray(bitNum);
  }

  public void addBit(int bitValue) {
    // this.bits is old bit count, which is same as index of new last bit
    if (this.buf.length <= arrayIndex(this.bits)) doubleBuf(); 
    ++this.bits;
    setBit(bitValue, this.bits-1);
  }

  int readBit(int bitNum) {  // return 0 or 1
    if (bitNum >= this.bits || bitNum < 0) throw new InvalidArgumentException();
    byte value = buf[arrayIndex(bitNum)] & ((byte)1 << bitNumInArray(bitNum));
    return (value == 0) ? 0 : 1;
  }

  void addBits(int bitCount, int bitValues) {
    for (int num = bitCount - 1 ; num >= 0 ; --num) {
      // change loop iteration order to change bit order of bitValues
      addBit(bitValues & (1 << num));
    }
}

对于有效的解决方案,它应该使用int或long数组而不是字节数组,并包含更有效的多位添加方法(一次添加bitValues整个buf数组元素的部分,不像上面一点一点地说。)

要保存此项,您需要保存来自buf的正确字节数,由getUsedArrayElements()计算。

相关问题