Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
写入和读取二进制文件java_Java - Fatal编程技术网

写入和读取二进制文件java

写入和读取二进制文件java,java,Java,我使用生成的哈夫曼代码压缩一个文本文件,然后将所有字符转换为0和1的字符串。使用以下代码在文件中编写它们。(输入为1011001110010011) 但是我在输出中得到了11101111111110110101101111111111111111111111111111011010011,我只是希望得到一些附加的0 编辑:将字符串更改为二进制代码,现在在末尾添加0以完成字节 public static void writeToFile(String binaryString, BufferedW

我使用生成的哈夫曼代码压缩一个文本文件,然后将所有字符转换为0和1的字符串。使用以下代码在文件中编写它们。(输入为
1011001110010011

但是我在输出中得到了
11101111111110110101101111111111111111111111111111011010011
,我只是希望得到一些附加的0

编辑:将字符串更改为二进制代码,现在在末尾添加0以完成字节

public static void writeToFile(String binaryString, BufferedWriter writer) throws IOException{
    int pos = 0;
    while(pos < binaryString.length()){
        byte nextByte = 0x00;
        for(int i=0;i<8; i++){
            nextByte = (byte) (nextByte << 1);
            if(pos+i < binaryString.length())
                nextByte += binaryString.charAt(pos+i)=='0'?0x0:0x1;
        }
        writer.write(nextByte);
        pos+=8;
    }
}
publicstaticvoidwritetofile(stringbinarystring,BufferedWriter-writer)抛出IOException{
int pos=0;
while(pos对于(int i=0;i而言,问题在于
BufferedWriter.write()
写入的是
char
,而不是
byte
。无论何时写入文件,都是一个可变大小的unicode字符,而不是一个
byte
,因此,文件中存储的内容将远远超出预期

你想用

new BufferedOutputStream(new FileOutputStream("filename"))
而是将方法的签名更改为采用
OutputStream


(您可能会注意到,
OutputStream.write()
接受的是
int
而不是
字节,但这只是让您感到困惑…它实际上只写入低阶字节,而不是整个
int
,因此它可以满足您的需要。)

提示:如果您一次将字符串拆分为8位,则
新的BigInteger(eightBitString,2).intValue()将为您提供相同的字节
public static void writeToFile(String binaryString, BufferedWriter writer) throws IOException{
    int pos = 0;
    while(pos < binaryString.length()){
        byte nextByte = 0x00;
        for(int i=0;i<8; i++){
            nextByte = (byte) (nextByte << 1);
            if(pos+i < binaryString.length())
                nextByte += binaryString.charAt(pos+i)=='0'?0x0:0x1;
        }
        writer.write(nextByte);
        pos+=8;
    }
}
new BufferedOutputStream(new FileOutputStream("filename"))