- 思路:
利用输入流和输出流进行文本的读出和写入,注意:压缩文件时会用到对象流(ObjectOutputStream写入文件),解压文件时,也会用到对象流(ObjectInputStream,读出文件)
- 代码:
//压缩文件
public void zipFile(String srcFile, String dstFile) {
InputStream is = null;
OutputStream os = null;
ObjectOutputStream oos = null;
try{
is = new FileInputStream(srcFile);
byte[] b = new byte[is.available()];
is.read(b);
byte[] hfmbytes = zip(b);
os = new FileOutputStream(dstFile);
oos = new ObjectOutputStream(os);
oos.writeObject(hfmbytes);
oos.writeObject(hashMap);
}catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}finally {
try {
is.close();
os.close();
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//解压文件
public void deZip(String srcFile, String dstFile ) {
InputStream is = null;
ObjectInputStream ois = null;
OutputStream os = null;
try {
is = new FileInputStream(srcFile);
ois = new ObjectInputStream(is);
byte[] hfmbytes = (byte[]) ois.readObject();
Map<Byte, String> hfmMap = (Map<Byte, String>) ois.readObject();
byte[] bytes1 = decode(hfmMap, hfmbytes);
os = new FileOutputStream(dstFile);
os.write(bytes1);
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}finally {
// TODO: handle finally clause
try {
is.close();
ois.close();
os.close();
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
}
}
注:
1、对于已经压缩好的文件,再使用哈夫曼压缩,效果不明显(比如视频、ppt等)。
2、哈夫曼编码是按照字节进行编码的,适用于所有文件。
3、对于内容重复不明显的文本,压缩效果不明显。