2014-11-03 81 views
0

我正在使用霍夫曼代碼壓縮文本文件,然後將所有字符轉換爲0和1的字符串。使用以下代碼將它們寫入文件中。 (輸入是1011001110010011寫入和讀取二進制文件java

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 && pos+i < binaryString.length(); i++){ 
      nextByte = (byte) (nextByte << 1); 
      nextByte += binaryString.charAt(pos+i)=='0'?0x0:0x1; 
     } 
     writer.write(nextByte); 
     pos+=8; 
    } 
} 

然後我試圖從我剛剛創建的文件重新生成以前的二進制串1011001110010011,使用下面的代碼

data = Files.readAllBytes(path); 
for(int i=0;i<data.length;i++){ 
    byte nextByte = data[i]; 
    String tempString = ""; 
    for(int j=0;j<8; j++){ 
     byte temp = (byte) (0x1 & nextByte); 
     if(temp==0x1){ 
      tempString="1".concat(tempString); 
     }else if(temp==0x0){ 
      tempString="0".concat(tempString); 
     } 
     nextByte = (byte) (nextByte >> 1); 
    } 
    binary=binary.concat(tempString); 
} 

但我在輸出了111011111011111010110011111011111011111010010011,我只是期待一些附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; 
    } 
} 
+0

提示:如果你一次把字符串分成8位,那麼'new BigInteger(eightBitString,2).intValue()'給你相同的字節 – weston 2014-11-03 08:54:15

回答

2

的問題是,BufferedWriter.write()寫入char,而不是一個byte。無論您何時寫入文件,都會寫入一個可變大小的unicode字符,而不是一個單獨的文件,所以您最終會以超出您預期的方式存儲在您的文件中。

你想用

new BufferedOutputStream(new FileOutputStream("filename")) 

,而是和改變你的方法的簽名,以採取OutputStream

(您可能注意到,OutputStream.write()需要一個int,而不是一個byte,但這是隻是爲了迷惑你......它實際上只寫入低位字節,而不是整個int,所以它做什麼你想要。)

+0

它的工作原理非常感謝。 – Ruturaj 2014-11-03 08:51:38

相關問題