本文共 2985 字,大约阅读时间需要 9 分钟。
/** * * @param srcFile 传入的需要压缩的文件的全路径 * @param dstFile 压缩文件的保存目录 */public static void zipFile(String srcFile,String dstFile){ //创建文件输入流,用于读取文件 FileInputStream is = null; OutputStream os = null; ObjectOutputStream oos = null; try { is = new FileInputStream(srcFile); byte[] b = new byte[is.available()]; is.read(b); //获取文件对应的霍夫曼编码 byte[] huffmanBytes = huffmanZip(b); //创建文件的输出流,准备存放文件 os = new FileOutputStream(dstFile); //创建一个和文件输出流相关的ObjectOutputStream oos = new ObjectOutputStream(os); //以对象流的方式及那个霍夫曼编码后的字节数组写入压缩文件 oos.writeObject(huffmanBytes); //同时注意一定要将压缩的霍夫曼编码写入文件 //以对象流的方式写入霍夫曼编码,为的是以后恢复原文件使用 oos.writeObject(huffmanCodes); } catch (Exception e) { System.out.println(e.getMessage()); }finally { try { is.close(); oos.close(); os.close(); } catch (IOException e) { e.printStackTrace(); } }}
解压文件
//编写一个方法,完成对压缩文件的解压 public static void unZipFile(String zipFile,String desFile){ //定义文件输入流 InputStream is = null; ObjectInputStream ois = null; OutputStream os = null; try { //创建文件输入流 is = new FileInputStream(zipFile); //创建一个和is关联的对象输入流 ois = new ObjectInputStream(is); //读取byte数组,huffmanBytes byte[] huffmanBytes = (byte[])ois.readObject(); //读取霍夫曼编码表 MaphuffmanCodes = (Map )ois.readObject(); //解码 byte[] bytes = decode(huffmanCodes,huffmanBytes); //将bytes数组写入到目标文件 os = new FileOutputStream(desFile); //写数据到desFile文件中去 os.write(bytes); }catch (Exception e){ System.out.println(e.getMessage()); }finally { try { is.close(); os.close(); ois.close(); } catch (IOException e) { e.printStackTrace(); } } }
结点流:基本四大类
处理流:包覆在节点流上面的,用于处理加工,改变节点流的流
抽象基类 | 字节流 | 字符流 |
---|---|---|
输入流 | InputStream | Reader |
输出流 | OutputStream | Writer |
霍夫曼编码压缩文件的注意事项
转载地址:http://qqgpb.baihongyu.com/