简体   繁体   English

用Java读取和写入位到文本文件

[英]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. 我正在尝试实现一些压缩算法,并且需要处理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. 我需要做的是,当我写入值1然后是值2时,这些数字将作为位存储在文件中,因此文件大小将是1字节而不是2,因为1存储在1位中,而2是存储在2位中。

Is it possible? 可能吗? Thanks very much 非常感谢

All the I/O methods have a byte as the lowest granularity. 所有I / O方法都有一个字节作为最低粒度。 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. 您也可以在Google上搜索“ BitOutputStream”,其中有一些,尽管不是很常见的库中。 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...) 最后,您将要创建的文件将不是“文本”文件,它将是非常二进制的(甚至比平时还要多...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM