📄 compress.java
字号:
package logical;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class Compress {
String[] code = new String[256];
Node[] tree;
String textName = null; // The name of the file that needs to be compressed
String fileName = null; // The name of the compressed file
public Compress(String textName, String fileName) throws IOException {
this.textName = textName;
this.fileName = fileName;
init();
}
public void init() throws IOException {
Reader reader = new Reader(textName); // Read a new file
this.code = reader.getHuffmanCode(); // Get the huffman code of the
// file
this.tree = reader.getHuffmanTree(); // Get the huffman tree of the
// file
this.creatCompressedFile(); // Creat the compressed file
}
private void creatCompressedFile() throws IOException {
// Read the file that needs to be compressed
BufferedInputStream input = new BufferedInputStream(
new FileInputStream(textName));
ObjectOutputStream output = new ObjectOutputStream(
new FileOutputStream(fileName));
// Read the tree of the file
output.writeObject(tree);
int temp; // store the byte that be read from the file
StringBuffer content = new StringBuffer(); // store the content
int addLength; // store the length that should be added in the tail
/** According to the code, translate them into the byte */
while ((temp = input.read()) != -1) {
content.append(this.code[temp]);
int length = content.length() >> 3;
for (int i = 0; i < length; i++) {
output.write(B2U(content.substring(0, 8))); // write the bytes
// into the file
content.delete(0, 8);
}
}
if (content.length() == 0)
addLength = 0;
else {
// Add 0's at the end of the content
addLength = 8 - content.length();
for (int i = 0; i < addLength; i++) {
content.append('0');
}
output.write(B2U(content.substring(0, 8)));
content.delete(0, 8);
}
input.close();
output.close();
}
// Acoording the code, translate them into unsign int
public int B2U(String s) {
int value = 0;
for (int i = 0; i < 8; i++) {
if (s.charAt(i) == '1') {
value += 0x1 << (7 - i);
}
}
return value;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -