Is it possible to read/write bits from a file using JAVA?

后端 未结 9 924
一生所求
一生所求 2020-12-09 21:34

To read/write binary files, I am using DataInputStream/DataOutputStream, they have this method writeByte()/readByte(), but what I want to do is read/write bits? Is it possib

相关标签:
9条回答
  • 2020-12-09 22:23

    The below code should work

        int[] mynumbers = {3,4};
        BitSet compressedNumbers = new BitSet(mynumbers.length*3);
        // let's say you encoded 3 as 101 and 4 as 010
        String myNumbersAsBinaryString = "101010"; 
        for (int i = 0; i < myNumbersAsBinaryString.length(); i++) {
            if(myNumbersAsBinaryString.charAt(i) == '1')
                compressedNumbers.set(i);
        }
        String path = Resources.getResource("myfile.out").getPath();
        ObjectOutputStream outputStream = null;
        try {
            outputStream = new ObjectOutputStream(new FileOutputStream(path));
            outputStream.writeObject(compressedNumbers);
        } catch (IOException e) {
            e.printStackTrace();
        }
    
    0 讨论(0)
  • 2020-12-09 22:24

    It's not possible to read/write individual bits directly, the smallest unit you can read/write is a byte.

    You can use the standard bitwise operators to manipulate a byte though, so e.g. to get the lowest 2 bits of a byte, you'd do

    byte b = in.readByte();
    byte lowBits = b&0x3;
    

    set the low 4 bits to 1, and write the byte:

    b |= 0xf;
    out.writeByte(b);
    

    (Note, for the sake of efficiency you might want to read/write byte arrays and not single bytes)

    0 讨论(0)
  • 2020-12-09 22:25

    Bits are packaged in bytes and apart from VHDL/Verilog I have seen no language that allows you to append individual bits to a stream. Cache up your bits and pack them into a byte for a write using a buffer and bitmasking. Do the reverse for read, i.e. keep a pointer in your buffer and increment it as you return individually masked bits.

    0 讨论(0)
提交回复
热议问题