decompression.java

来自「基于哈夫曼树的压缩解压程序源代码」· Java 代码 · 共 71 行

JAVA
71
字号
package logical;

import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class Decompression {

	Node[] tree = new Node[256];

	String textName = null;

	Node root;

	String DecompressTextName;

	ObjectInputStream input;

	BufferedOutputStream output;

	public Decompression(String textName, String DecompressTextName)
			throws IOException, ClassNotFoundException {
		this.textName = textName;
		this.DecompressTextName = DecompressTextName;
		init();
	}

	public void init() throws IOException, ClassNotFoundException {

		input = new ObjectInputStream(new FileInputStream(textName));
		output = new BufferedOutputStream(new FileOutputStream(
				DecompressTextName));
		// Read the huffman tree from the file
		tree = (Node[]) input.readObject();
		creatDecompressionFile();
	}

	private void creatDecompressionFile() throws IOException {

		int temp;
		root = tree[tree.length - 1]; // Get the root
		Node tempNode = root; // Search from the root

		while ((temp = input.read()) != -1) {

			for (int i = 0; i < 8; i++) {
				// read the bits,according the bits,find the value of the Node
				if (((temp >> (7 - i)) & 1) == 0) {
					// get 0,then search from the left child
					tempNode = tempNode.getLeftChild();
				} else {
					// get 1, then search from the right child
					tempNode = tempNode.getRightChild();
				}
				if (tempNode.isLeaf()) {
					output.write(tempNode.getValue());
					// restart the seach.
					tempNode = root;
				}
			}

		}
		input.close();
		output.close();

	}

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?