GZip压缩解压

来源:互联网 发布:notepad格式化json 编辑:程序博客网 时间:2024/05/29 18:52
import java.awt.Label;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.FileInputStream;import java.io.FileOutputStream;import java.util.zip.GZIPInputStream;import java.util.zip.GZIPOutputStream;import javax.swing.*;public class GZipDemo extends JFrame{JFileChooser fileChooser;JTextField source;JTextField target;JButton select1;JButton select2;JButton jbZip;JButton jbUnZip;public GZipDemo(){super("用GZip压缩解压文件");fileChooser=new JFileChooser();source=new JTextField(16);target=new JTextField(16);select1=new JButton("选择");select2=new JButton("选择");jbZip =new JButton("压缩");jbUnZip=new JButton("解压");Box box=Box.createVerticalBox();JPanel panel=new JPanel();panel.add(new Label("源文件"));panel.add(source);panel.add(select1);box.add(panel);panel=new JPanel();panel.add(new JLabel("目标文件"));panel.add(target);panel.add(select2);box.add(panel);panel=new JPanel();panel.add(jbZip);panel.add(jbUnZip);box.add(panel);getContentPane().add(box);jbZip.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubzipFile(source.getText(),target.getText());}});jbUnZip.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubunZipFile(source.getText(),target.getText());}});select1.addActionListener(new SelectListener());select2.addActionListener(new SelectListener());setSize(330,150);setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}public void zipFile(String source,String target){try{FileInputStream in=new FileInputStream(source);FileOutputStream out=new FileOutputStream(target);GZIPOutputStream gzout=new GZIPOutputStream(out);byte[] buf=new byte[1024];int num;while((num=in.read(buf))!=-1){gzout.write(buf,0,num);}gzout.close();out.close();in.close();JOptionPane.showMessageDialog(GZipDemo.this, "压缩成功");}catch(Exception e){e.printStackTrace();JOptionPane.showMessageDialog(GZipDemo.this,"解压失败");}}public void unZipFile(String source,String target){try{FileInputStream in=new FileInputStream(source);FileOutputStream out=new FileOutputStream(target);GZIPInputStream gzin=new GZIPInputStream(in);byte[] buf=new byte[1024];int num;while((num=gzin.read(buf,0,buf.length))!=-1){out.write(buf,0,num);}gzin.close();out.close();in.close();JOptionPane.showMessageDialog(GZipDemo.this,"解压成功");}catch(Exception e){e.printStackTrace();JOptionPane.showMessageDialog(GZipDemo.this,"解压失败");}}class SelectListener implements ActionListener{public void actionPerformed(ActionEvent e){if(fileChooser.showOpenDialog(GZipDemo.this)==JFileChooser.APPROVE_OPTION){String fileName=fileChooser.getSelectedFile().getAbsolutePath();if(e.getSource().equals(select1)){source.setText(fileName);}else{target.setText(fileName);}}}}public static void main(String[] args){new GZipDemo();}}

0 0
原创粉丝点击