제 6단계 디코딩하기
class HuffmanDecoder
public class HuffmanDecoder {
static public void main (String args[]) {
String fileName = "";
HuffmanCoding app = new HuffmanCoding();
RandomAccessFile fIn;
Scanner kb = new Scanner(System.in);
try {
System.out.print("Enter a file name: ");
fileName = kb.next();
fIn = new RandomAccessFile(fileName,"r");
app.decompressFile(fileName,fIn);
fIn.close();
} catch (IOException io) {
System.err.println("Cannot open " + fileName);
}
}
}
//실제 추가할 함수
decompressFile
public void decompressFile(String inFileName, RandomAccessFile fIn)
throws IOException {
String outFileName = new String(inFileName+".dec");
RandomAccessFile fOut = new
RandomAccessFile(outFileName,"rw");
inputFrequencies(fIn);
createHuffmanTree();
assignCodewords(theRoot,0,0);
decode(fIn,fOut);
}
inputFrequencies
private void inputFrequencies(RandomAccessFile fIn)
throws IOException {
int dataIndex = fIn.readInt();
sizeOriginalFile = fIn.readLong();
runs.ensureCapacity(dataIndex);
for (int j = 0; j < dataIndex; j++) {
Run r = new Run();
r.symbol = (byte) fIn.read();
r.runLen = fIn.readInt();
r.freq = fIn.readInt();
runs.add(r);
}
}
decode
private void decode(RandomAccessFile fIn, RandomAccessFile fOut)
throws IOException {
//Fin = 압축파일
int nbrBytesRead=0, j, ch, bitCnt = 1, mask = 1, bits = 8;
mask <<= bits - 1; // change 00000001 to 100000000
for (ch=fIn.read(); ch!=-1 && nbrBytesRead<sizeOriginalFile;) {
Run p = theRoot;
while(true) {
if (p.left == null && p.right == null) {
for (j = 0; j < p.runLen; j++)
fOut.write(p.symbol);
nbrBytesRead += p.runLen;
break;
}
else if ((ch & mask) == 0) /* if the most significant bit is 0 */
p = p.left;
else /* if the most significant bit is 1 */
p = p.right;
if (bitCnt++ == bits) { /* if done with the current byte */
ch = fIn.read();
bitCnt = 1;
}
else
ch <<= 1; /* left-shift the current byte */
}
}
}
댓글
댓글 쓰기