以前为了了解哈夫曼树,而做的一个文件压缩的东东,,实现给文件压缩,与解压
话不多多说先上图,当然界面不是非常的亮,有关界面的问题,上面两篇博客已经写得很清楚了!
关键压缩技术是哈弗曼树的压缩,所谓哈弗曼树详细猛戳此网址
http://baike.baidu.com/view/127820.htm
我定义的文件格式如下
编码数 出现的字节 字节编码的长度 字节的编码 码表
代码
这个是哈弗曼节点类
一个节点有数据,权值(也就是出现的频率),左子树,右子树
- package hfyasuo;
- publicclass HfmNode {
- publicint Data;
- publicint Times;
- public HfmNode Lc;
- public HfmNode Rc;
- public HfmNode(int Data,int Times){
- this.Data=Data;
- this.Times=Times;
- }
- }
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;
}
}
首先你得得到你要压缩文件的里面每个字节出现的个数
- //统计文件各字节数字数
- publicint[] getByteCounts() throws IOException{
- int[] bc=newint[256];
- FileInputStream in=new FileInputStream(file);
- while(in.available()>0){
- bc[in.read()]++;
- }
- in.close();
- return bc;
- }
//统计文件各字节数字数
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
之后就可以根据各字节出现的数字开始构造哈夫曼树
- publicint 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;
- }
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());
存储节点,然后在根据哈夫曼数的特点来构造哈夫曼树
其中优先队列重写他的比较方法,这里应该是比较节点的次数
- package hfyasuo;
- import java.util.Comparator;
- publicclass Mycomparator implements Comparator<HfmNode>{
- @Override
- publicint compare(HfmNode n1, HfmNode n2) {
- // TODO Auto-generated method stub
- if(n1.Times<n2.Times){
- return -1;
- }elseif(n1.Times>n2.Times){
- return1;
- }else{
- return0;}
- }
- }
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;}
}
}
树构建好后,现在开始获取编码
- //构造,获取各字节的编码
- publicvoid 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);
- }
- }
//构造,获取各字节的编码
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,这岂不是就达到了压缩嘛,也就是将不足八位的编码凑成八位写入
- //写入文件的总数,写入节点数,写入出现的字节,每个字节的编码长度,写入码表,写入文件的编码
- publicvoid 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编码
- publicint 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));
- }
//写入文件的总数,写入节点数,写入出现的字节,每个字节的编码长度,写入码表,写入文件的编码
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));
}
/********************************************下面是解压**********************************************************************/
解压就是逆过程,不多介绍,看代码
- /************************开始解压*****************************/
- public FileInputStream Fp;
- public DataInputStream Dafp;
- publicint Hfmcounts=0;
- publicvoid k(String Pressedfile) throws IOException{
- Fp=new FileInputStream(Pressedfile);
- Dafp=new DataInputStream(Fp);
- }
- //得到文件总数
- publicint getFileCounts() throws Exception{
- int Filecounts;
- Filecounts=Dafp.readInt();
- return Filecounts;
- }
- //得到节点数
- publicint getHfmcounts() throws IOException{
- Hfmcounts=Fp.read();
- return Hfmcounts;
- }
- //得到的码表中的字节
- publicbyte[] getBytes() throws IOException{
- //System.out.println("========>"+Hfmcounts);
- byte[] by=newbyte[Hfmcounts];
- Fp.read(by,0,Hfmcounts);
- return by ;
- }
- //得到字节的长度
- publicbyte[] getCodeLenths() throws IOException{
- byte[] by=newbyte[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=newint[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);
- }
- }elseif(c2==0){
- int[] Codes=newint[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=newchar[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;
- }
- //解压文件
- publicvoid 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();
- }
- }
/************************开始解压*****************************/
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();
}
}
主要方法就是这些,下面就是界面了
- publicclass Jframe extends JFrame implements ActionListener{
- public Cop c;
- public Jframe(Cop c){
- this.c=c;
- }
- publicvoid 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
- */
- publicstaticvoid main(String[] args) {
- // TODO Auto-generated method stub
- Cop c=new Cop();
- Jframe j=new Jframe(c);
- j.UI();
- }
- @Override
- publicvoid 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();
- }
- }
- //解压过程
- elseif(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();
- }
- };
- }
- }
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 也可以留言