📄 decompress.java
字号:
package org.galaxy_OPEN.www.datastructures.huffman;
import java.io.*;
public class Decompress {
private HuffmanFrame hfRef;
private ObjectInputStream ois;
private DataOutputStream dos;
private FileHeader fileHeader;
private Node huffTree;
private long bytesWritten;
private Node currentByteValue;
private String outPath;
private File tmpFile;
public Decompress(HuffmanFrame hf, String inPath, String outPath)
throws FileNotFoundException, IOException {
hfRef = hf;
bytesWritten = 0;
this.outPath = outPath;
tmpFile = new File(outPath);
ois = new ObjectInputStream(new FileInputStream(inPath));
dos = new DataOutputStream(new FileOutputStream(outPath));
}
private void readHeader() throws IOException, ClassNotFoundException {
fileHeader = (FileHeader) ois.readObject();
huffTree = fileHeader.getHuffmanTree();
currentByteValue = huffTree;
String name = fileHeader.getOriginalFileName();
int extIndex = name.indexOf(".");
String ext = name.substring(extIndex);
if (dos != null) {
dos.close();
}
if (tmpFile != null) {
tmpFile.delete();
}
dos = new DataOutputStream(new FileOutputStream(outPath + ext));
}
private void decode(byte[] data) throws IOException {
byte toWrite;
int posi;
for (int i = 0; i < data.length; i++) {
byte leByte = data[i];
for (int j = 7; j >= 0; j--) {
if (((leByte >>> j) & 0x1) == 0)
currentByteValue = currentByteValue.getLeftChild();
else
currentByteValue = currentByteValue.getRightChild();
if (currentByteValue.isLeaf()) {
posi = currentByteValue.getPosition();
toWrite = (byte) (posi >= 128 ? posi - 256 : posi);
dos.writeByte(toWrite); // On l'ecrit
bytesWritten++;
if (bytesWritten == fileHeader.getNumBytes())
return;
currentByteValue = huffTree;
}
}
}
}
public void decode() throws IOException, ClassNotFoundException {
hfRef.setMessage(hfRef.getFile().getPath() + " 正在解压缩……");
byte[] data;
readHeader();
int numBytesLeft = ois.available();
while (numBytesLeft > 0) {
data = new byte[numBytesLeft];
ois.read(data);
decode(data);
numBytesLeft = ois.available();
}
ois.close();
dos.flush();
dos.close();
hfRef.setMessage(hfRef.getFile().getPath() + " 解压缩完成!");
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -