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

后端 未结 9 925
一生所求
一生所求 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();
        }
    

提交回复
热议问题