开发者

Reading and Writing Bits to Text Files in Java

I'm trying to implement some compression algorithms, and I need to deal with bits in Java.

What I need to do is that when I write the value 1 then the value 2, those numbers are stored in the file as bits, so the file size will be 1 byte instead of 2, as 1 is stored in 1 bit and 2 is stored in 2 bits.

Is it possible? Thanks very开发者_如何学JAVA much


All the I/O methods have a byte as the lowest granularity. You can write bits, but you have to pack them into bytes by yourself. Maybe a one-byte buffer that you write out to the file once it fills up would be appropriate.

Also note that there is no way to know the length of the file in bits (you do not know if the last byte was "full"). So your application needs to take care of that somehow.

You can also google for "BitOutputStream", of which there are a few, though not in libraries that are very common. Maybe just use one of those.

Finally, the file you will be creating will not be a "Text" file, it will be very much binary (even more so than usual...)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜