我正在使用霍夫曼代碼壓縮文本文件,然後將所有字符轉換爲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;
}
}
提示:如果你一次把字符串分成8位,那麼'new BigInteger(eightBitString,2).intValue()'給你相同的字節 – weston 2014-11-03 08:54:15