`
师大黄飞
  • 浏览: 44348 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

Java基础之文件压缩解压工具

阅读更多

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

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



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

我定义的文件格式如下

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

代码

这个是哈弗曼节点类

一个节点有数据,权值(也就是出现的频率),左子树,右子树

Java代码 复制代码
  1. package hfyasuo;
  2. publicclass HfmNode {
  3. publicint Data;
  4. publicint Times;
  5. public HfmNode Lc;
  6. public HfmNode Rc;
  7. public HfmNode(int Data,int Times){
  8. this.Data=Data;
  9. 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代码 复制代码
  1. //统计文件各字节数字数
  2. publicint[] getByteCounts() throws IOException{
  3. int[] bc=newint[256];
  4. FileInputStream in=new FileInputStream(file);
  5. while(in.available()>0){
  6. bc[in.read()]++;
  7. }
  8. in.close();
  9. 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代码 复制代码
  1. publicint HfmCounts=0;
  2. //构建哈弗曼树,返回树的根节点
  3. public HfmNode CreatHfmNode() throws IOException{
  4. //构建队列,将节点加入队列
  5. PriorityQueue<HfmNode> hfmshu=new PriorityQueue<HfmNode>(1,new Mycomparator());
  6. int[] bc=getByteCounts();
  7. for(int i=0;i<256;i++){
  8. if(bc[i]!=0){
  9. 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()>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<HfmNode> hfmshu=new PriorityQueue<HfmNode>(1,new Mycomparator());

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

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

Java代码 复制代码
  1. package hfyasuo;
  2. import java.util.Comparator;
  3. publicclass Mycomparator implements Comparator<HfmNode>{
  4. @Override
  5. publicint compare(HfmNode n1, HfmNode n2) {
  6. // TODO Auto-generated method stub
  7. if(n1.Times<n2.Times){
  8. return -1;
  9. }elseif(n1.Times>n2.Times){
  10. return1;
  11. }else{
  12. return0;}
  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代码 复制代码
  1. //构造,获取各字节的编码
  2. publicvoid getCode(HfmNode Root,String s){
  3. if(Root.Lc!=null){
  4. getCode(Root.Lc,s+'0');
  5. }
  6. if(Root.Rc!=null){
  7. getCode(Root.Rc,s+'1');
  8. }
  9. 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代码 复制代码
  1. //写入文件的总数,写入节点数,写入出现的字节,每个字节的编码长度,写入码表,写入文件的编码
  2. publicvoid writeBytesCodes() throws IOException{
  3. FileInputStream in=new FileInputStream(file);//获取文件的输入流
  4. FileOutputStream ou=new FileOutputStream(Pressedfile);
  5. DataOutputStream Daou=new DataOutputStream(ou);
  6. Daou.writeInt(in.available());//写入文件的总数
  7. ou.write(HfmCounts);//写入节点总数
  8. //System.out.println("写入的字节总数是"+HfmCounts);
  9. //写入出现过的字节
  10. int[] bc=getByteCounts();
  11. for(int i=0;i<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<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<256;l++){
  31. if(Code[l]==null){
  32. Code[l]="";
  33. }
  34. }
  35. //凑成八位写入
  36. while(counts>=8||i<256){
  37. if(counts<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>0){
  50. //System.out.println("此时的s"+s);
  51. int len=8-counts;
  52. for(int j=0;j<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>=8||In.available()>0){
  65. if(fcounts<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>0){
  78. int len=8-fcounts;
  79. for(int j=0;j<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. publicint 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代码 复制代码
  1. /************************开始解压*****************************/
  2. public FileInputStream Fp;
  3. public DataInputStream Dafp;
  4. publicint Hfmcounts=0;
  5. publicvoid k(String Pressedfile) throws IOException{
  6. Fp=new FileInputStream(Pressedfile);
  7. Dafp=new DataInputStream(Fp);
  8. }
  9. //得到文件总数
  10. publicint getFileCounts() throws Exception{
  11. int Filecounts;
  12. Filecounts=Dafp.readInt();
  13. return Filecounts;
  14. }
  15. //得到节点数
  16. publicint getHfmcounts() throws IOException{
  17. Hfmcounts=Fp.read();
  18. return Hfmcounts;
  19. }
  20. //得到的码表中的字节
  21. publicbyte[] getBytes() throws IOException{
  22. //System.out.println("========>"+Hfmcounts);
  23. byte[] by=newbyte[Hfmcounts];
  24. Fp.read(by,0,Hfmcounts);
  25. return by ;
  26. }
  27. //得到字节的长度
  28. publicbyte[] getCodeLenths() throws IOException{
  29. byte[] by=newbyte[Hfmcounts];
  30. Fp.read(by,0,Hfmcounts);
  31. return by ;
  32. }
  33. //得到码表编码
  34. public String[] getCodes() throws IOException{
  35. byte[] By=getCodeLenths();
  36. int count=0;
  37. for(int i=0;i<Hfmcounts;i++){
  38. count+=By[i];
  39. }
  40. String[] sCode=new String[Hfmcounts];
  41. int c1=count/8;
  42. int c2=count%8;
  43. int c=8-c2;
  44. //System.out.println("------>zhengza"+c1);
  45. String s="";
  46. if(c2!=0){
  47. c1+=1;
  48. int[] Codes=newint[c1];
  49. //Codes[0]= Fp.read();
  50. for(int i=0;i<c1;i++){
  51. Codes[i]=Fp.read();
  52. s+=changeint(Codes[i]);
  53. //System.out.println("++++"+s);
  54. }
  55. if(c1!=0){
  56. s=s.substring(0,s.length()-c);
  57. }
  58. }elseif(c2==0){
  59. int[] Codes=newint[c1];
  60. for(int i=0;i<c1;i++){
  61. Codes[i]=Fp.read();
  62. s+=changeint(Codes[i]);
  63. //System.out.println("----"+s);
  64. }
  65. }
  66. int k=0;
  67. int y=0;
  68. for(int i=0;i<Hfmcounts;i++){
  69. y=k+By[i];
  70. sCode[i]=s.substring(k,y);
  71. //System.out.println(y+"hhh"+sCode[i]);
  72. k=y;
  73. }
  74. return sCode;
  75. }
  76. //得到文件编码
  77. public String getFileCodes() throws Exception{
  78. //
  79. String s="";
  80. while(Fp.available()>0){
  81. s+=changeint(Fp.read());
  82. }
  83. return s;
  84. }
  85. //将01编码转换成01串
  86. public String changeint(int k){
  87. char [] st=newchar[8];
  88. String s="";
  89. int i=7;
  90. //String sk="";
  91. while(k!=0){
  92. st[i]=(char)(k%2+48);
  93. k=k/2;
  94. i--;
  95. }
  96. for(int j=i+1;j<8;j++){
  97. s+=st[j];
  98. }
  99. for(int ks=7-i;ks<8;ks++){
  100. s="0"+s;
  101. }
  102. return s;
  103. }
  104. //解压文件
  105. publicvoid 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<Filecounts&&count<=FileCodes.length()){
  122. String s=FileCodes.substring(c,count);
  123. //System.out.println(s);
  124. for(int j=0;j<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代码 复制代码
  1. publicclass Jframe extends JFrame implements ActionListener{
  2. public Cop c;
  3. public Jframe(Cop c){
  4. this.c=c;
  5. }
  6. publicvoid UI(){
  7. this.setTitle("黄飞压缩工具");
  8. this.setSize(400, 200);
  9. this.setLocationRelativeTo(null);//让窗体居中
  10. this.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getClassLoader().getResource("头像.png")));
  11. this.setDefaultCloseOperation(3);
  12. //this.setAlwaysOnTop(true);
  13. //构建一个JPanel面板
  14. JPanel panel=new JPanel();
  15. BoxLayout layout=new BoxLayout(panel, BoxLayout.Y_AXIS);//箱式布局,按照Y轴往下排列
  16. panel.setLayout(layout);
  17. //按钮,标签
  18. JButton jb1=new JButton(" 压缩 ");
  19. jb1.setActionCommand("压缩");
  20. JLabel jl=new JLabel("选择你要执行的功能");
  21. JButton jb2=new JButton(" 解压 ");
  22. jb2.setActionCommand("解压");
  23. //居中排列
  24. jb1.setAlignmentX(Component.CENTER_ALIGNMENT);
  25. jl.setAlignmentX(Component.CENTER_ALIGNMENT);
  26. jb2.setAlignmentX(Component.CENTER_ALIGNMENT);
  27. //把组件加到面板上
  28. panel.add(jb1);
  29. panel.add(jl);
  30. panel.add(jb2);
  31. this.add(panel);
  32. //加入监听器
  33. jb1.addActionListener(this);
  34. jb2.addActionListener(this);
  35. this.setVisible(true);
  36. }
  37. /**
  38. * @param args
  39. */
  40. publicstaticvoid main(String[] args) {
  41. // TODO Auto-generated method stub
  42. Cop c=new Cop();
  43. Jframe j=new Jframe(c);
  44. j.UI();
  45. }
  46. @Override
  47. publicvoid actionPerformed(ActionEvent e) {
  48. // 压缩过程
  49. if(e.getActionCommand().equals("压缩")){
  50. //压缩选择,跳出文件选择器,选择要压缩的文件
  51. JOptionPane.showMessageDialog(null,"选择要压缩的文件");
  52. JFileChooser chooser = new JFileChooser();
  53. chooser.setFileSelectionMode(JFileChooser.OPEN_DIALOG );//打开型
  54. chooser.setApproveButtonText("压缩");//设置一个压缩按钮
  55. chooser.showDialog(null, null);//弹出选择器
  56. c.file=chooser.getSelectedFile();//得到要压缩的文件
  57. //保存过程
  58. JOptionPane.showMessageDialog(null,"选择要保存的路径");
  59. JFileChooser ch = new JFileChooser();
  60. ch.setFileSelectionMode(JFileChooser.SAVE_DIALOG );//保存类型
  61. ch.setApproveButtonText("保存");//保存按钮
  62. ch.showDialog(null, null);//弹出窗口
  63. //得到出去扩展名的文件名
  64. int ii=c.file.getName().lastIndexOf(".");
  65. String str=c.file.getName().substring(0,ii);
  66. //得到压缩后的文件
  67. File f=new File(ch.getSelectedFile(),str+".hf");
  68. c.Pressedfile=f;
  69. try {
  70. f.createNewFile();//创建压缩后的文件
  71. c.Compressfile();//压缩开始
  72. JOptionPane.showMessageDialog(null,"压缩完毕");
  73. } catch (IOException e1) {
  74. // TODO Auto-generated catch block
  75. e1.printStackTrace();
  76. }
  77. }
  78. //解压过程
  79. elseif(e.getActionCommand().equals("解压")){
  80. //解压过程,同上
  81. JOptionPane.showMessageDialog(null,"选择要解缩的文件");
  82. JFileChooser chooser = new JFileChooser("wenjian");
  83. chooser.setFileSelectionMode(JFileChooser.OPEN_DIALOG );
  84. chooser.setApproveButtonText("解压");
  85. FileNameExtensionFilter filter = new FileNameExtensionFilter("hf","hf");
  86. chooser.setFileFilter(filter);
  87. chooser.showDialog(null, null);
  88. c.Pressedfile=chooser.getSelectedFile();
  89. //保存
  90. JOptionPane.showMessageDialog(null, "选择解压文件的保存路径");
  91. JFileChooser ch = new JFileChooser("wenjian");
  92. ch.setFileSelectionMode(JFileChooser.SAVE_DIALOG );
  93. ch.setApproveButtonText("保存");
  94. ch.showDialog(null, null);
  95. int ii=c.Pressedfile.getName().lastIndexOf(".");
  96. String str=c.Pressedfile.getName().substring(0,ii);
  97. File f=new File(ch.getSelectedFile(),str+".txt");
  98. try {
  99. 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 也可以留言

  • 大小: 18.4 KB
  • 大小: 4.3 KB
7
8
分享到:
评论

相关推荐

    java 中 zip压缩文件解压工具类

    在Java编程环境中,处理文件压缩和解压缩是常见的任务,特别是在构建可执行的JAR包或者处理数据传输时。本文将深入探讨如何使用Java来处理ZIP文件,特别是针对标题所提及的“java 中 zip压缩文件解压工具类”。我们...

    Java基础之文件压缩器

    下面我们将详细讲解相关的Java文件压缩知识。 首先,Java中的文件压缩主要依赖于Java标准库中的`java.util.zip`包,该包提供了用于压缩和解压缩文件的类,如`ZipOutputStream`和`ZipInputStream`。这两个类分别用于...

    使用 Java 实现的压缩/解压 ZIP 文件的工具类

    在Java编程环境中,处理文件压缩和解压任务是常见的需求,尤其在数据传输或存储时。ZIP文件格式因其广泛支持和高效性而被广泛应用。本文将深入探讨如何使用Java实现ZIP文件的压缩与解压,重点讲解核心API,如`java....

    java压缩文件工具类

    将文件打包成压缩文件,以及对压缩包的解压,方便好用。

    java文件解压缩工具箱及案例

    本主题将深入探讨如何使用Java来创建一个文件解压缩工具箱,特别关注支持ZIP和RAR格式,并解决中文乱码问题。首先,我们需要了解两个核心库:`java-unrar-1.7.0-1.jar` 和 `ant-1.8.2.jar`。 `java-unrar-1.7.0-1....

    java ftp上传 下载 文件压缩解压

    这篇博客“java ftp上传 下载 文件压缩解压”很可能是关于如何使用Java实现FTP文件上传、下载以及文件的压缩与解压功能。下面我们将深入探讨这些知识点。 首先,FTP上传和下载是Java中常见的任务,通常通过`java...

    java自动解压缩文件

    Java自动解压缩文件是编程领域中的一个重要话题,尤其是在服务器端应用中,经常需要处理上传的压缩文件并进行解压操作。Java提供了丰富的API来支持这一功能,主要涉及到`java.util.zip`包中的类,如`ZipInputStream`...

    java文件分割压缩

    Java文件分割压缩是一种常见的操作,尤其在处理大数据或者网络传输时非常有用,因为单个大文件可能会导致处理效率低或传输困难。以下是一些相关的Java编程知识点: 1. **文件I/O操作**:在Java中,`java.io`包提供...

    java操作压缩文件和解压文件实例代码(经测试)

    1. **Java ZIP API**:Java标准库提供了`java.util.zip`包,该包包含了处理ZIP文件的各种类,如`ZipOutputStream`用于压缩,`ZipInputStream`用于解压缩。`ZipEntry`类代表ZIP文件中的一个条目,可以用来添加或读取...

    java 基于WinRAR6.02封装的压缩及分卷压缩工具

    可以进行单压缩或分卷压缩(后续会基于WinRAR6.02版本封装解压工具) 支持功能: 1,设置压缩密码(设置解压密码或压缩文件打开密码,默认没有密码) 2,设置五种压缩方式(存储、最快、快速、标准、较好、最优,默认为标准) 3...

    java压缩文件解压缩和文件的压缩

    在Java编程语言中,处理...通过以上这些知识点,你可以构建一个强大的Java工具类,实现ZIP和RAR文件的压缩与解压缩,包括处理加密的ZIP文件。这个工具类可以是项目中一个可靠的助手,提高代码的可重用性和可维护性。

    Java用GZIP压缩解压文件源码

    在Java编程语言中,GZIP是一种常用的文件压缩格式,...了解并掌握这些基础知识对于进行Java文件处理和数据传输是非常重要的。同时,根据项目需求,你可能还需要考虑其他优化和错误处理策略,以确保代码的健壮性和效率。

    Java版开源Winzip压缩工具源码

    通过研究这个开源项目,开发者不仅可以了解Java文件处理和压缩技术,还能学习到软件开发的最佳实践,包括代码结构、测试策略和团队协作方式,从而提升自己的专业技能。对于想要自己开发类似工具或者在现有项目中集成...

    JAVA实现的文件压缩

    通过以上步骤,我们可以利用Java SWING创建一个用户友好的文件压缩工具,实现文件或文件夹的压缩功能。这种实现不仅适用于个人项目,也可以作为企业级应用的基础模块,提升软件的功能性和用户体验。

    java解压zip压缩文件

    在Java编程环境中,解压ZIP压缩文件是一项常见的任务,它涉及到文件I/O操作以及对ZIP文件格式的理解。本文将深入探讨如何使用Java实现这一功能,同时也会提及`UnZip.java`和`UnZip2.java`这两个文件可能包含的实现...

    JAVA文件压缩与解压缩实践(源代码+论文).zip

    总之,掌握Java文件压缩与解压缩技术对于任何Java开发者来说都是必要的技能,无论是在日常开发还是在特定项目中,这都是一项实用的工具。通过研究提供的源代码和论文,你将能深入理解这一技术,并能够灵活地将其应用...

    java源码:文件压缩解压缩包 Commons Compress.rar

    这个库是由 Apache 软件基金会开发的,是 Java 平台上处理压缩和归档文件的标准工具之一。在 Java 开发中,如果需要处理 ZIP、GZIP、BZIP2、7z、ARJ、TAR、CPIO、RAR 等多种压缩格式,Apache Commons Compress 库是...

    文件压缩解压缩

    在IT行业中,文件压缩与解压缩是日常工作中常见的操作,特别是在数据传输、存储优化和软件分发等领域。这里我们主要探讨的是一个简单的工具类,它支持zip、rar、tar等多种格式的压缩和解压缩功能,并且经过实际测试...

    Java 实现图形化文件解压缩工具(支持加解密哦)

    在Java编程领域,开发一个基于Swing的图形化文件解压缩工具是一项常见的任务,尤其当这个工具还支持文件的加解密功能时,其技术挑战性和实用性就更上一层楼。下面将详细介绍如何利用Java来实现这样的功能。 首先,...

Global site tag (gtag.js) - Google Analytics