---
title: "Java基础之文件压缩解压工具"
author: "师大黄飞"
date: "2014-01-07T21:54:03Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2015-03-29T11:33:22Z"
id: 2000975
url: "https://505860922.iteye.com/blog/2000975"
---

以前为了了解哈夫曼树，而做的一个文件压缩的东东，，实现给文件压缩，与解压

话不多多说先上图，当然界面不是非常的亮，有关界面的问题，上面两篇博客已经写得很清楚了！

![](http://dl2.iteye.com/upload/attachment/0092/8577/dcf57b2b-3bf7-3088-98ef-57979f2ca479.png)

![](http://dl2.iteye.com/upload/attachment/0092/8575/a9851e99-0528-34d4-810e-4893a6bc269b.png)

关键压缩技术是哈弗曼树的压缩，所谓哈弗曼树详细猛戳此网址  
[http://baike.baidu.com/view/127820.htm](http://baike.baidu.com/view/127820.htm "哈弗曼树")

我定义的文件格式如下

编码数 出现的字节 字节编码的长度 字节的编码 码表

代码

这个是哈弗曼节点类

一个节点有数据，权值（也就是出现的频率），左子树，右子树

Java代码 [![复制代码](/images/icon_copy.gif)](/admin/blogs/1999629 "复制代码")

01. **package** hfyasuo;
02. **public****class** HfmNode {
03. **public****int** Data;
04. **public****int** Times;
05. **public** HfmNode Lc;
06. **public** HfmNode Rc;
07. **public** HfmNode(**int** Data,**int** Times){
08. **this**.Data=Data;
09. **this**.Times=Times;
10. }
11. }

```
package hfyasuo;  
  
public class HfmNode {  
public int Data;  
public int Times;  
public HfmNode Lc;  
public HfmNode Rc;  
public HfmNode(int Data,int Times){  
    this.Data=Data;  
    this.Times=Times;  
}  
}
```

 

首先你得得到你要压缩文件的里面每个字节出现的个数

Java代码 [![复制代码](/images/icon_copy.gif)](/admin/blogs/1999629 "复制代码")

01. //统计文件各字节数字数
02. **public****int**\[] getByteCounts() **throws** IOException{
03. **int**\[] bc=**new****int**\[256];
04. FileInputStream in=**new** FileInputStream(file);
05. **while**(in.available()&gt;0){
06. bc\[in.read()]++;
07. }
08. in.close();
09. **return** bc;
10. }

```
//统计文件各字节数字数  
public int[] getByteCounts() throws IOException{  
    int[] bc=new int[256];  
    FileInputStream in=new FileInputStream(file);  
    while(in.available()>0){  
        bc[in.read()]++;  
    }  
    in.close();  
    return bc;  
}  
```

用一个数组存储起来，如果存在某个字节那么就次数+1

之后就可以根据各字节出现的数字开始构造哈夫曼树

Java代码 [![复制代码](/images/icon_copy.gif)](/admin/blogs/1999629 "复制代码")

01. **public****int** HfmCounts=0;
02. //构建哈弗曼树，返回树的根节点
03. **public** HfmNode CreatHfmNode() **throws** IOException{
04. //构建队列，将节点加入队列
05. PriorityQueue&lt;HfmNode&gt; hfmshu=**new** PriorityQueue&lt;HfmNode&gt;(1,**new** Mycomparator());
06. **int**\[] bc=getByteCounts();
07. **for**(**int** i=0;i&lt;256;i++){
08. **if**(bc\[i]!=0){
09. HfmNode h=**new** HfmNode(i,bc\[i]);
10. hfmshu.add(h);
11. HfmCounts++;
12. }
13. }
14. //System.out.println("产生了"+HfmCounts+"个节点");
15. //构建哈弗曼树
16. **while**(hfmshu.size()&gt;1){
17. HfmNode h1=hfmshu.poll();
18. HfmNode h2=hfmshu.poll();
19. HfmNode hh=**new** HfmNode(h1.Data+h2.Data,h1.Times+h2.Times);
20. hh.Lc=h1;
21. hh.Rc=h2;
22. hfmshu.add(hh);
23. }
24. //获取根节点
25. HfmNode Root=hfmshu.peek();
26. **return** Root;
27. }

```
public int HfmCounts=0;  
//构建哈弗曼树，返回树的根节点  
public HfmNode CreatHfmNode() throws IOException{  
    //构建队列，将节点加入队列  
    PriorityQueue<HfmNode> hfmshu=new PriorityQueue<HfmNode>(1,new  Mycomparator());  
    int[] bc=getByteCounts();  
    for(int i=0;i<256;i++){  
        if(bc[i]!=0){  
            HfmNode h=new HfmNode(i,bc[i]);  
            hfmshu.add(h);  
            HfmCounts++;  
        }  
    }  
    //System.out.println("产生了"+HfmCounts+"个节点");  
    //构建哈弗曼树  
    while(hfmshu.size()>1){  
    HfmNode h1=hfmshu.poll();  
    HfmNode h2=hfmshu.poll();  
    HfmNode hh=new HfmNode(h1.Data+h2.Data,h1.Times+h2.Times);  
    hh.Lc=h1;  
    hh.Rc=h2;  
    hfmshu.add(hh);  
    }  
    //获取根节点  
    HfmNode Root=hfmshu.peek();  
    return Root;  
}  
```

利用优先队列PriorityQueue&lt;HfmNode&gt; hfmshu=new PriorityQueue&lt;HfmNode&gt;(1,new Mycomparator());

存储节点，然后在根据哈夫曼数的特点来构造哈夫曼树

其中优先队列重写他的比较方法，这里应该是比较节点的次数

Java代码 [![复制代码](/images/icon_copy.gif)](/admin/blogs/1999629 "复制代码")

01. **package** hfyasuo;
02. **import** java.util.Comparator;
03. **public****class** Mycomparator **implements** Comparator&lt;HfmNode&gt;{
04. @Override
05. **public****int** compare(HfmNode n1, HfmNode n2) {
06. // TODO Auto-generated method stub
07. **if**(n1.Times&lt;n2.Times){
08. **return** -1;
09. }**else****if**(n1.Times&gt;n2.Times){
10. **return**1;
11. }**else**{
12. **return**0;}
13. }
14. }

```
package hfyasuo;  
  
import java.util.Comparator;  
  
  
  
  
public class Mycomparator implements Comparator<HfmNode>{  
  
    @Override  
    public int compare(HfmNode n1, HfmNode n2) {  
        // TODO Auto-generated method stub  
        if(n1.Times<n2.Times){  
            return -1;  
        }else if(n1.Times>n2.Times){  
            return 1;  
        }else{  
        return 0;}  
    }  
  
      
  
}  
```

树构建好后，现在开始获取编码

Java代码 [![复制代码](/images/icon_copy.gif)](/admin/blogs/1999629 "复制代码")

01. //构造,获取各字节的编码
02. **public****void** getCode(HfmNode Root,String s){
03. **if**(Root.Lc!=**null**){
04. getCode(Root.Lc,s+'0');
05. }
06. **if**(Root.Rc!=**null**){
07. getCode(Root.Rc,s+'1');
08. }
09. **if**(Root.Lc==**null**&&Root.Rc==**null**){
10. Code\[Root.Data]=s;
11. //System.out.println("得到了一个编码"+Root.data+' '+s);
12. }
13. }

```
//构造,获取各字节的编码  
public void getCode(HfmNode Root,String s){  
    if(Root.Lc!=null){  
          getCode(Root.Lc,s+'0');  
    }  
    if(Root.Rc!=null){  
         getCode(Root.Rc,s+'1');  
    }  
    if(Root.Lc==null&&Root.Rc==null){  
         Code[Root.Data]=s;  
         //System.out.println("得到了一个编码"+Root.data+' '+s);  
    }     
    }  
```

 

接下来，就是要按照自己的定义的格式将编码写入到文件当中，写入的信息必须要保证能将其按照规则解压

那么要实现到压缩，就必得动些手脚，，写入最少是一个字节一个字节的写入（一个字节是八位），就是byte为最小单位，现在我们是要写入编码，比如说得到的三个编码是010 110 01100一般写入是要是三个字节，就是写入00000010

00000110 0001100这三个字节，但是如果我们将这三个字节作为一个字节存入，就是写入01011001100，这岂不是就达到了压缩嘛，也就是将不足八位的编码凑成八位写入

Java代码 [![复制代码](/images/icon_copy.gif)](/admin/blogs/1999629 "复制代码")

01. //写入文件的总数,写入节点数，写入出现的字节,每个字节的编码长度,写入码表,写入文件的编码
02. **public****void** writeBytesCodes() **throws** IOException{
03. FileInputStream in=**new** FileInputStream(file);//获取文件的输入流
04. FileOutputStream ou=**new** FileOutputStream(Pressedfile);
05. DataOutputStream Daou=**new** DataOutputStream(ou);
06. Daou.writeInt(in.available());//写入文件的总数
07. ou.write(HfmCounts);//写入节点总数
08. //System.out.println("写入的字节总数是"+HfmCounts);
09. //写入出现过的字节
10. **int**\[] bc=getByteCounts();
11. **for**(**int** i=0;i&lt;256;i++){
12. **if**(bc\[i]!=0){
13. ou.write(i);
14. // System.out.println("写入的码表字节是"+i);
15. }
16. }
17. //写入每个编码的长度
18. **for**(**int** i=0;i&lt;256;i++){
19. **if**(Code\[i]!=**null**){
20. ou.write(Code\[i].length());
21. //System.out.println("写入的编码长度是"+Code\[i].length());
22. }
23. }
24. //写入码表
25. **int** counts=0;
26. **int** i=0;
27. String s="";
28. String writes;
29. //首先对码表进行处理
30. **for**(**int** l=0;l&lt;256;l++){
31. **if**(Code\[l]==**null**){
32. Code\[l]="";
33. }
34. }
35. //凑成八位写入
36. **while**(counts&gt;=8||i&lt;256){
37. **if**(counts&lt;8){
38. s+=Code\[i];
39. counts=s.length();
40. i++;
41. }**else**{
42. writes=s.substring(0,8);
43. ou.write(changeString(writes));
44. counts=counts-8;
45. s=s.substring(8);
46. //System.out.println(s);
47. }
48. }
49. **if**(counts&gt;0){
50. //System.out.println("此时的s"+s);
51. **int** len=8-counts;
52. **for**(**int** j=0;j&lt;len;j++){
53. s=s+"0";
54. }
55. ou.write(changeString(s));
56. //System.out.println(len+"写入的编码是k"+s);
57. }
58. //写入文件的编码
59. FileInputStream In=**new** FileInputStream(file);
60. **int** fcounts=0;
61. //int fi=0;
62. String fs="";
63. String fwrites;
64. **while**(fcounts&gt;=8||In.available()&gt;0){
65. **if**(fcounts&lt;8){
66. **int** ii=In.read();
67. fs+=Code\[ii];
68. fcounts=fs.length();
69. //System.out.println(ii+" "+Code\[ii]);
70. }**else**{
71. fwrites=fs.substring(0,8);
72. ou.write(changeString(fwrites));
73. fcounts=fcounts-8;
74. fs=fs.substring(8);
75. }
76. }
77. **if**(fcounts&gt;0){
78. **int** len=8-fcounts;
79. **for**(**int** j=0;j&lt;len;j++){
80. fs=fs+"0";
81. }
82. ou.write(changeString(fs));
83. //System.out.println("写入的文件编码是k"+fs);
84. }
85. //压缩结束
86. in.close();
87. In.close();
88. Daou.close();
89. }
90. //将01字符串转换为01编码
91. **public****int** changeString(String s){
92. **return** (((**int**)s.charAt(0)-48)\*128+((**int**)s.charAt(1)-48)\*64+((**int**)s.charAt(2)-48)\*32+((**int**)s.charAt(3)-48)\*16+((**int**)s.charAt(4)-48)\*8+((**int**)s.charAt(5)-48)\*4+((**int**)s.charAt(6)-48)\*2+((**int**)s.charAt(7)-48));
93. }

```
//写入文件的总数,写入节点数，写入出现的字节,每个字节的编码长度,写入码表,写入文件的编码  
public void writeBytesCodes() throws IOException{  
    FileInputStream in=new FileInputStream(file);//获取文件的输入流  
    FileOutputStream ou=new FileOutputStream(Pressedfile);  
    DataOutputStream Daou=new DataOutputStream(ou);  
    Daou.writeInt(in.available());//写入文件的总数  
    ou.write(HfmCounts);//写入节点总数  
    //System.out.println("写入的字节总数是"+HfmCounts);  
    //写入出现过的字节  
    int[] bc=getByteCounts();  
    for(int i=0;i<256;i++){  
        if(bc[i]!=0){  
         ou.write(i);  
        // System.out.println("写入的码表字节是"+i);  
        }  
    }  
    //写入每个编码的长度  
    for(int i=0;i<256;i++){  
        if(Code[i]!=null){  
            ou.write(Code[i].length());  
           //System.out.println("写入的编码长度是"+Code[i].length());  
        }  
    }  
    //写入码表  
    int counts=0;  
    int i=0;  
    String s="";  
    String writes;  
    //首先对码表进行处理  
    for(int l=0;l<256;l++){  
        if(Code[l]==null){  
            Code[l]="";  
        }  
    }  
    //凑成八位写入  
    while(counts>=8||i<256){  
        if(counts<8){  
            s+=Code[i];  
            counts=s.length();  
            i++;  
        }else{  
            writes=s.substring(0,8);  
            ou.write(changeString(writes));  
            counts=counts-8;  
            s=s.substring(8);  
            //System.out.println(s);  
        }  
        }  
    if(counts>0){  
        //System.out.println("此时的s"+s);  
        int len=8-counts;  
        for(int j=0;j<len;j++){  
            s=s+"0";  
        }  
        ou.write(changeString(s));  
        //System.out.println(len+"写入的编码是k"+s);  
    }  
    //写入文件的编码  
    FileInputStream In=new FileInputStream(file);  
    int fcounts=0;  
    //int fi=0;  
    String fs="";  
    String fwrites;  
    while(fcounts>=8||In.available()>0){  
        if(fcounts<8){  
            int ii=In.read();  
            fs+=Code[ii];  
            fcounts=fs.length();  
            //System.out.println(ii+" "+Code[ii]);  
        }else{  
            fwrites=fs.substring(0,8);  
            ou.write(changeString(fwrites));  
            fcounts=fcounts-8;  
            fs=fs.substring(8);  
        }  
    }  
    if(fcounts>0){  
        int len=8-fcounts;  
        for(int j=0;j<len;j++){  
            fs=fs+"0";  
        }  
        ou.write(changeString(fs));  
        //System.out.println("写入的文件编码是k"+fs);  
    }  
    //压缩结束  
    in.close();  
    In.close();  
    Daou.close();  
    }  
//将01字符串转换为01编码  
    public int changeString(String s){  
        return (((int)s.charAt(0)-48)*128+((int)s.charAt(1)-48)*64+((int)s.charAt(2)-48)*32+((int)s.charAt(3)-48)*16+((int)s.charAt(4)-48)*8+((int)s.charAt(5)-48)*4+((int)s.charAt(6)-48)*2+((int)s.charAt(7)-48));  
    }  
```

/\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*下面是解压\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*/

解压就是逆过程，不多介绍，看代码

Java代码 [![复制代码](/images/icon_copy.gif)](/admin/blogs/1999629 "复制代码")

001. /\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*开始解压\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*/
002. **public** FileInputStream Fp;
003. **public** DataInputStream Dafp;
004. **public****int** Hfmcounts=0;
005. **public****void** k(String Pressedfile) **throws** IOException{
006. Fp=**new** FileInputStream(Pressedfile);
007. Dafp=**new** DataInputStream(Fp);
008. }
009. //得到文件总数
010. **public****int** getFileCounts() **throws** Exception{
011. **int** Filecounts;
012. Filecounts=Dafp.readInt();
013. **return** Filecounts;
014. }
015. //得到节点数
016. **public****int** getHfmcounts() **throws** IOException{
017. Hfmcounts=Fp.read();
018. **return** Hfmcounts;
019. }
020. //得到的码表中的字节
021. **public****byte**\[] getBytes() **throws** IOException{
022. //System.out.println("========&gt;"+Hfmcounts);
023. **byte**\[] by=**new****byte**\[Hfmcounts];
024. Fp.read(by,0,Hfmcounts);
025. **return** by ;
026. }
027. //得到字节的长度
028. **public****byte**\[] getCodeLenths() **throws** IOException{
029. **byte**\[] by=**new****byte**\[Hfmcounts];
030. Fp.read(by,0,Hfmcounts);
031. **return** by ;
032. }
033. //得到码表编码
034. **public** String\[] getCodes() **throws** IOException{
035. **byte**\[] By=getCodeLenths();
036. **int** count=0;
037. **for**(**int** i=0;i&lt;Hfmcounts;i++){
038. count+=By\[i];
039. }
040. String\[] sCode=**new** String\[Hfmcounts];
041. **int** c1=count/8;
042. **int** c2=count%8;
043. **int** c=8-c2;
044. //System.out.println("------&gt;zhengza"+c1);
045. String s="";
046. **if**(c2!=0){
047. c1+=1;
048. **int**\[] Codes=**new****int**\[c1];
049. //Codes\[0]= Fp.read();
050. **for**(**int** i=0;i&lt;c1;i++){
051. Codes\[i]=Fp.read();
052. s+=changeint(Codes\[i]);
053. //System.out.println("++++"+s);
054. }
055. **if**(c1!=0){
056. s=s.substring(0,s.length()-c);
057. }
058. }**else****if**(c2==0){
059. **int**\[] Codes=**new****int**\[c1];
060. **for**(**int** i=0;i&lt;c1;i++){
061. Codes\[i]=Fp.read();
062. s+=changeint(Codes\[i]);
063. //System.out.println("----"+s);
064. }
065. }
066. **int** k=0;
067. **int** y=0;
068. **for**(**int** i=0;i&lt;Hfmcounts;i++){
069. y=k+By\[i];
070. sCode\[i]=s.substring(k,y);
071. //System.out.println(y+"hhh"+sCode\[i]);
072. k=y;
073. }
074. **return** sCode;
075. }
076. //得到文件编码
077. **public** String getFileCodes() **throws** Exception{
078. //
079. String s="";
080. **while**(Fp.available()&gt;0){
081. s+=changeint(Fp.read());
082. }
083. **return** s;
084. }
085. //将01编码转换成01串
086. **public** String changeint(**int** k){
087. **char** \[] st=**new****char**\[8];
088. String s="";
089. **int** i=7;
090. //String sk="";
091. **while**(k!=0){
092. st\[i]=(**char**)(k%2+48);
093. k=k/2;
094. i--;
095. }
096. **for**(**int** j=i+1;j&lt;8;j++){
097. s+=st\[j];
098. }
099. **for**(**int** ks=7-i;ks&lt;8;ks++){
100. s="0"+s;
101. }
102. **return** s;
103. }
104. //解压文件
105. **public****void** ReleaseFile() **throws** Exception{
106. k(Pressedfile.getAbsolutePath());
107. FileOutputStream fo=**new** FileOutputStream(Releasedfile);
108. **int** count=1;
109. **int** c=0;
110. **int** Filecounts=getFileCounts();
111. getHfmcounts();
112. //System.out.println(Filecounts);
113. **byte**\[] CodeBytes=getBytes();
114. //System.out.println(CodeBytes\[0]+""+CodeBytes\[1]+""+CodeBytes\[2]);
115. String\[] Codes=getCodes();
116. //System.out.println(Codes\[0]+""+Codes\[1]+""+Codes\[2]);
117. String FileCodes=getFileCodes();
118. //System.out.println(FileCodes+" "+Filecounts);
119. **int** i=0;
120. //int k=0;
121. **while**(i&lt;Filecounts&&count&lt;=FileCodes.length()){
122. String s=FileCodes.substring(c,count);
123. //System.out.println(s);
124. **for**(**int** j=0;j&lt;Codes.length;j++){
125. **if**(s.equals(Codes\[j])){
126. fo.write(CodeBytes\[j]);
127. c=count;
128. //System.out.println("pppp"+CodeBytes\[j]);
129. i++;
130. }
131. }
132. count++;
133. }
134. fo.close();
135. }
136. }

```
/************************开始解压*****************************/  
    public FileInputStream Fp;  
    public DataInputStream Dafp;  
    public int Hfmcounts=0;  
    public void k(String Pressedfile) throws IOException{  
        Fp=new FileInputStream(Pressedfile);  
        Dafp=new DataInputStream(Fp);  
    }  
    //得到文件总数  
    public int getFileCounts() throws Exception{  
        int Filecounts;  
          
        Filecounts=Dafp.readInt();  
          
        return Filecounts;  
    }  
    //得到节点数  
    public int getHfmcounts() throws IOException{  
         Hfmcounts=Fp.read();  
        return Hfmcounts;  
    }  
    //得到的码表中的字节  
    public byte[] getBytes() throws IOException{  
        //System.out.println("========>"+Hfmcounts);  
        byte[] by=new byte[Hfmcounts];  
        Fp.read(by,0,Hfmcounts);  
        return by ;  
    }  
    //得到字节的长度  
    public byte[] getCodeLenths() throws IOException{  
        byte[] by=new byte[Hfmcounts];  
        Fp.read(by,0,Hfmcounts);  
        return by ;  
    }  
    //得到码表编码  
    public String[] getCodes() throws IOException{  
        byte[] By=getCodeLenths();  
        int count=0;  
        for(int i=0;i<Hfmcounts;i++){  
            count+=By[i];  
        }  
      
        String[] sCode=new String[Hfmcounts];  
        int c1=count/8;  
        int c2=count%8;  
        int c=8-c2;  
        //System.out.println("------>zhengza"+c1);  
        String s="";  
        if(c2!=0){  
            c1+=1;  
            int[] Codes=new int[c1];  
            //Codes[0]= Fp.read();  
            for(int i=0;i<c1;i++){  
                Codes[i]=Fp.read();  
                s+=changeint(Codes[i]);  
                //System.out.println("++++"+s);  
            }  
            if(c1!=0){  
            s=s.substring(0,s.length()-c);  
            }  
        }else if(c2==0){  
            int[] Codes=new int[c1];  
            for(int i=0;i<c1;i++){  
                Codes[i]=Fp.read();  
                s+=changeint(Codes[i]);  
                //System.out.println("----"+s);  
            }  
        }  
        int k=0;  
        int y=0;  
        for(int i=0;i<Hfmcounts;i++){  
            y=k+By[i];  
            sCode[i]=s.substring(k,y);  
            //System.out.println(y+"hhh"+sCode[i]);  
            k=y;  
        }  
        return sCode;  
    }  
    //得到文件编码  
    public String getFileCodes() throws Exception{  
        //  
        String s="";  
        while(Fp.available()>0){  
            s+=changeint(Fp.read());  
        }  
        return s;  
    }  
    //将01编码转换成01串  
    public String changeint(int k){  
        char [] st=new char[8];  
        String s="";  
        int i=7;  
        //String sk="";  
        while(k!=0){  
            st[i]=(char)(k%2+48);  
            k=k/2;  
            i--;  
        }  
        for(int j=i+1;j<8;j++){  
            s+=st[j];  
        }  
        for(int ks=7-i;ks<8;ks++){  
            s="0"+s;  
        }  
        return s;  
    }  
    //解压文件  
        public void ReleaseFile() throws Exception{  
             k(Pressedfile.getAbsolutePath());  
            FileOutputStream fo=new FileOutputStream(Releasedfile);  
            int count=1;  
            int c=0;  
            int Filecounts=getFileCounts();  
            getHfmcounts();  
            //System.out.println(Filecounts);  
            byte[] CodeBytes=getBytes();  
            //System.out.println(CodeBytes[0]+""+CodeBytes[1]+""+CodeBytes[2]);  
            String[] Codes=getCodes();  
            //System.out.println(Codes[0]+""+Codes[1]+""+Codes[2]);  
            String FileCodes=getFileCodes();  
            //System.out.println(FileCodes+"  "+Filecounts);  
            int i=0;  
            //int k=0;  
            while(i<Filecounts&&count<=FileCodes.length()){  
                String s=FileCodes.substring(c,count);  
                //System.out.println(s);  
                for(int j=0;j<Codes.length;j++){  
                    if(s.equals(Codes[j])){  
                        fo.write(CodeBytes[j]);  
                        c=count;  
                        //System.out.println("pppp"+CodeBytes[j]);  
                        i++;  
                    }  
                }  
                count++;  
            }  
            fo.close();  
        }  
  
        }  
```

主要方法就是这些，下面就是界面了

Java代码 [![复制代码](/images/icon_copy.gif)](/admin/blogs/1999629 "复制代码")

001. **public****class** Jframe **extends** JFrame **implements** ActionListener{
002. **public** Cop c;
003. **public** Jframe(Cop c){
004. **this**.c=c;
005. }
006. **public****void** UI(){
007. **this**.setTitle("黄飞压缩工具");
008. **this**.setSize(400, 200);
009. **this**.setLocationRelativeTo(**null**);//让窗体居中
010. **this**.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getClassLoader().getResource("头像.png")));
011. **this**.setDefaultCloseOperation(3);
012. //this.setAlwaysOnTop(true);
013. //构建一个JPanel面板
014. JPanel panel=**new** JPanel();
015. BoxLayout layout=**new** BoxLayout(panel, BoxLayout.Y\_AXIS);//箱式布局，按照Y轴往下排列
016. panel.setLayout(layout);
017. //按钮，标签
018. JButton jb1=**new** JButton(" 压缩 ");
019. jb1.setActionCommand("压缩");
020. JLabel jl=**new** JLabel("选择你要执行的功能");
021. JButton jb2=**new** JButton(" 解压 ");
022. jb2.setActionCommand("解压");
023. //居中排列
024. jb1.setAlignmentX(Component.CENTER\_ALIGNMENT);
025. jl.setAlignmentX(Component.CENTER\_ALIGNMENT);
026. jb2.setAlignmentX(Component.CENTER\_ALIGNMENT);
027. //把组件加到面板上
028. panel.add(jb1);
029. panel.add(jl);
030. panel.add(jb2);
031. **this**.add(panel);
032. //加入监听器
033. jb1.addActionListener(**this**);
034. jb2.addActionListener(**this**);
035. **this**.setVisible(**true**);
036. }
037. /\**
038. \* @param args
039. \*/
040. **public****static****void** main(String\[] args) {
041. // TODO Auto-generated method stub
042. Cop c=**new** Cop();
043. Jframe j=**new** Jframe(c);
044. j.UI();
045. }
046. @Override
047. **public****void** actionPerformed(ActionEvent e) {
048. // 压缩过程
049. **if**(e.getActionCommand().equals("压缩")){
050. //压缩选择，跳出文件选择器，选择要压缩的文件
051. JOptionPane.showMessageDialog(**null**,"选择要压缩的文件");
052. JFileChooser chooser = **new** JFileChooser();
053. chooser.setFileSelectionMode(JFileChooser.OPEN\_DIALOG );//打开型
054. chooser.setApproveButtonText("压缩");//设置一个压缩按钮
055. chooser.showDialog(**null**, **null**);//弹出选择器
056. c.file=chooser.getSelectedFile();//得到要压缩的文件
057. //保存过程
058. JOptionPane.showMessageDialog(**null**,"选择要保存的路径");
059. JFileChooser ch = **new** JFileChooser();
060. ch.setFileSelectionMode(JFileChooser.SAVE\_DIALOG );//保存类型
061. ch.setApproveButtonText("保存");//保存按钮
062. ch.showDialog(**null**, **null**);//弹出窗口
063. //得到出去扩展名的文件名
064. **int** ii=c.file.getName().lastIndexOf(".");
065. String str=c.file.getName().substring(0,ii);
066. //得到压缩后的文件
067. File f=**new** File(ch.getSelectedFile(),str+".hf");
068. c.Pressedfile=f;
069. **try** {
070. f.createNewFile();//创建压缩后的文件
071. c.Compressfile();//压缩开始
072. JOptionPane.showMessageDialog(**null**,"压缩完毕");
073. } **catch** (IOException e1) {
074. // TODO Auto-generated catch block
075. e1.printStackTrace();
076. }
077. }
078. //解压过程
079. **else****if**(e.getActionCommand().equals("解压")){
080. //解压过程，同上
081. JOptionPane.showMessageDialog(**null**,"选择要解缩的文件");
082. JFileChooser chooser = **new** JFileChooser("wenjian");
083. chooser.setFileSelectionMode(JFileChooser.OPEN\_DIALOG );
084. chooser.setApproveButtonText("解压");
085. FileNameExtensionFilter filter = **new** FileNameExtensionFilter("hf","hf");
086. chooser.setFileFilter(filter);
087. chooser.showDialog(**null**, **null**);
088. c.Pressedfile=chooser.getSelectedFile();
089. //保存
090. JOptionPane.showMessageDialog(**null**, "选择解压文件的保存路径");
091. JFileChooser ch = **new** JFileChooser("wenjian");
092. ch.setFileSelectionMode(JFileChooser.SAVE\_DIALOG );
093. ch.setApproveButtonText("保存");
094. ch.showDialog(**null**, **null**);
095. **int** ii=c.Pressedfile.getName().lastIndexOf(".");
096. String str=c.Pressedfile.getName().substring(0,ii);
097. File f=**new** File(ch.getSelectedFile(),str+".txt");
098. **try** {
099. f.createNewFile();
100. c.Releasedfile=f;
101. System.out.println(f.getAbsolutePath());
102. c.ReleaseFile();
103. JOptionPane.showMessageDialog(**null**,"解压完毕");
104. // c.ReleaseFile();
105. } **catch** (IOException e1) {
106. // TODO Auto-generated catch block
107. e1.printStackTrace();
108. } **catch** (Exception e1) {
109. // TODO Auto-generated catch block
110. e1.printStackTrace();
111. }
112. };
113. }
114. }

```
public class Jframe extends JFrame implements ActionListener{  
    public Cop c;  
    public Jframe(Cop c){  
        this.c=c;  
    }  
public void UI(){  
    this.setTitle("黄飞压缩工具");  
    this.setSize(400, 200);  
    this.setLocationRelativeTo(null);//让窗体居中  
    this.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getClassLoader().getResource("头像.png")));  
    this.setDefaultCloseOperation(3);  
    //this.setAlwaysOnTop(true);  
    //构建一个JPanel面板  
     JPanel panel=new JPanel();   
     BoxLayout layout=new BoxLayout(panel, BoxLayout.Y_AXIS);//箱式布局，按照Y轴往下排列   
     panel.setLayout(layout);  
     //按钮，标签  
     JButton jb1=new JButton("    压缩           ");  
     jb1.setActionCommand("压缩");  
     JLabel jl=new JLabel("选择你要执行的功能");  
     JButton jb2=new JButton("    解压           ");  
     jb2.setActionCommand("解压");  
     //居中排列  
     jb1.setAlignmentX(Component.CENTER_ALIGNMENT);  
     jl.setAlignmentX(Component.CENTER_ALIGNMENT);  
     jb2.setAlignmentX(Component.CENTER_ALIGNMENT);  
     //把组件加到面板上  
     panel.add(jb1);  
     panel.add(jl);  
     panel.add(jb2);  
     this.add(panel);  
     //加入监听器  
     jb1.addActionListener(this);  
     jb2.addActionListener(this);  
     this.setVisible(true);  
}  
    /** 
     * @param args 
     */  
    public static void main(String[] args) {  
        // TODO Auto-generated method stub  
       Cop c=new Cop();  
       Jframe j=new Jframe(c);  
       j.UI();  
    }  
    @Override  
    public void actionPerformed(ActionEvent e) {  
        // 压缩过程  
        if(e.getActionCommand().equals("压缩")){  
            //压缩选择，跳出文件选择器，选择要压缩的文件  
           JOptionPane.showMessageDialog(null,"选择要压缩的文件");  
           JFileChooser chooser = new JFileChooser();  
           chooser.setFileSelectionMode(JFileChooser.OPEN_DIALOG );//打开型  
           chooser.setApproveButtonText("压缩");//设置一个压缩按钮  
           chooser.showDialog(null, null);//弹出选择器  
           c.file=chooser.getSelectedFile();//得到要压缩的文件  
          //保存过程  
           JOptionPane.showMessageDialog(null,"选择要保存的路径");  
           JFileChooser ch = new JFileChooser();  
           ch.setFileSelectionMode(JFileChooser.SAVE_DIALOG );//保存类型  
           ch.setApproveButtonText("保存");//保存按钮  
           ch.showDialog(null, null);//弹出窗口  
           //得到出去扩展名的文件名  
           int ii=c.file.getName().lastIndexOf(".");  
           String str=c.file.getName().substring(0,ii);  
           //得到压缩后的文件  
           File f=new File(ch.getSelectedFile(),str+".hf");  
           c.Pressedfile=f;  
           try {  
            f.createNewFile();//创建压缩后的文件  
            c.Compressfile();//压缩开始  
             JOptionPane.showMessageDialog(null,"压缩完毕");  
        } catch (IOException e1) {  
            // TODO Auto-generated catch block  
            e1.printStackTrace();  
        }  
        }  
        //解压过程  
        else if(e.getActionCommand().equals("解压")){  
             //解压过程，同上  
              JOptionPane.showMessageDialog(null,"选择要解缩的文件");  
              JFileChooser chooser = new JFileChooser("wenjian");  
               chooser.setFileSelectionMode(JFileChooser.OPEN_DIALOG );  
               chooser.setApproveButtonText("解压");  
               FileNameExtensionFilter filter = new FileNameExtensionFilter("hf","hf");  
               chooser.setFileFilter(filter);  
               chooser.showDialog(null, null);  
               c.Pressedfile=chooser.getSelectedFile();  
               //保存  
               JOptionPane.showMessageDialog(null, "选择解压文件的保存路径");  
               JFileChooser ch = new JFileChooser("wenjian");  
               ch.setFileSelectionMode(JFileChooser.SAVE_DIALOG );  
               ch.setApproveButtonText("保存");  
               ch.showDialog(null, null);  
               int ii=c.Pressedfile.getName().lastIndexOf(".");  
               String str=c.Pressedfile.getName().substring(0,ii);  
               File f=new File(ch.getSelectedFile(),str+".txt");  
               try {  
                f.createNewFile();  
                c.Releasedfile=f;  
                 System.out.println(f.getAbsolutePath());  
                 c.ReleaseFile();  
                 JOptionPane.showMessageDialog(null,"解压完毕");  
                // c.ReleaseFile();   
            } catch (IOException e1) {  
                // TODO Auto-generated catch block  
                e1.printStackTrace();  
            } catch (Exception e1) {  
                // TODO Auto-generated catch block  
                e1.printStackTrace();  
            }  
                
                 
        };  
    }  
  
}  
```

界面主要就是一个文件选择器JFileChooser 的应用，查看API就能具体了解

同样源代码已经上传，不懂可以联系我，55860922 也可以留言

- [![](http://dl2.iteye.com/upload/attachment/0092/8575/a9851e99-0528-34d4-810e-4893a6bc269b-thumb.png "点击查看原始大小图片")](http://dl2.iteye.com/upload/attachment/0092/8575/a9851e99-0528-34d4-810e-4893a6bc269b.png)
- 大小: 18.4 KB

<!--THE END-->

- [![](http://dl2.iteye.com/upload/attachment/0092/8577/dcf57b2b-3bf7-3088-98ef-57979f2ca479-thumb.png "点击查看原始大小图片")](http://dl2.iteye.com/upload/attachment/0092/8577/dcf57b2b-3bf7-3088-98ef-57979f2ca479.png)
- 大小: 4.3 KB