Java 基于java.util.zip类压缩解压Zip文件

  • Windows 系统下的压缩解压软件Winzip,想必大家都用过或听说过。本例将利用java.util.zip 包中提供的类来实现压缩和解压zip 格式文件的功能。当然,本例在功能上完全没有Winzip 等成熟的压缩软件那么强,也不能做的很强,本例仅仅是演示如何来使用java.util.zip 包中的类。其效果如下图所示,窗口下部的“Start”按钮控制压缩和解压的开始。当源文件是zip 格式时,如“d:\bois.zip”,表示这次操作是解压,因而目标文件将是一个目录,如“d:\aa”;当源文件是非zip 格式的文件时,表示此次操作是压缩,因而目标文件是一个zip 格式的文件。

    Java 压缩解压Zip文件

    实现方法和思路:先来看java.util.zip 包中的几个类:

    1.ZipEntry 类表示zip 文件中的一个压缩文件或文件夹。一般可以利用如下的构造方法来创建一个该类对象(用于文件压缩时):

    1 public ZipEntry(String name)
    2 //参数name 表示压缩的文件或目录的名称。

    2.ZipFile 类用来从一个zip 文件中读取所有ZipEntry 对象。创建实例的构造方法:

    1 public ZipFile(File file)
    2 public ZipFile(String name)

    参数file 表示File 对象表示的zip 文件,参数name 表示路径表示的zip 文件。读取ZipEntry 对象的方法:

    1 public Enumeration entries()

    返回一个包含有所有ZipEntry对象的Enumeration对象。使用Enumeration类的nextElement()方法得到ZipEntry 对象:

    1 ZipEntry ze = (ZipEntry)enum.nextElement();

    enum 是Enumeration 类的实例。ZipFile 类中getInputStream()方法,可以打开一个ZipEntry 对象的输入流,用于解压文件。其原型如下:

    1 Public InputStream getInputStream(ZipEntry entry) throws IOException

    3.ZipOutputStream 类,该类可用来压缩文件。通过调用putNextEntry()方法,可以打开一个ZipEntry 对象的输出流,其原型如下:

    1 public void putNextEntry(ZipFile e) throws IOException

    本例中通过使用ZipEntry 和ZipFile 类及其他文件输入输出流类来实现解压;通过使用ZipEntry和ZipOutputStream 类及其他的文件输入输出流类实现压缩。本例的压缩和解压只限于一个文件的情况。
    程序代码
    1.新建一个Project,取名为JZipDemo。
    2.新建一个Application,取名为JZipDemo;主窗口取名为MainFrame,标题为JZipDemo。
    3.在MainFrame 类的设计窗口中添加一个JPanel 组件置于窗口的山部,并在其上添加两个
    JLabel 组件和两个JTextField 组件;在设计窗口的中部添加一个JScrollPane,并在其上添加一个JTextArea 组件;在设计窗口的下部添加一个JButton 组件,具体的实现代码如下:

    01 public class MainFrame extends JFrame {
    02 private JPanel contentPane;
    03 private BorderLayout borderLayout1 = new BorderLayout();
    04 private JScrollPane jScrollPane1 = new JScrollPane();
    05 private JTextArea jTextArea1 = new JTextArea();
    06 private JButton jButton1 = new JButton();
    07 private JPanel jPanel1 = new JPanel();
    08 private JTextField jTextField1 = new JTextField();
    09 private JTextField jTextField2 = new JTextField();
    10 private JLabel jLabel1 = new JLabel();
    11 private JLabel jLabel2 = new JLabel();
    12 private GridLayout gridLayout1 = new GridLayout();
    13 ……
    14 }

    4.编写MainFrame 类的初始化方法jbInit(),设置个组件的初始属性及相应的布局,添加JButton组件的事件监听器,代码如下:

    01 private void jbInit() throws Exception {
    02 //设置组件和窗口的属性布局,在窗口中添加这些组件
    03 //setIconImage(Toolkit.getDefaultToolkit().createImage(MainFrame.class.getResource("[Your Icon]")));
    04 contentPane = (JPanel) this.getContentPane();
    05 contentPane.setLayout(borderLayout1);
    06 this.setSize(new Dimension(461307));
    07 this.setTitle("JZipDemo");
    08 jTextArea1.setText("unzip and zip information");
    09 jButton1.setFont(new java.awt.Font("Dialog"014));
    10 jButton1.setToolTipText("");
    11 jButton1.setText("start");
    12 jButton1.addActionListener(new java.awt.event.ActionListener() {//添加JButton 的事件监听器
    13 public void actionPerformed(ActionEvent e) {
    14 jButton1_actionPerformed(e);
    15 }
    16 });
    17 jLabel1.setFont(new java.awt.Font("Dialog"012));
    18 jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
    19 jLabel1.setText("source path :");
    20 jLabel2.setFont(new java.awt.Font("Dialog"012));
    21 jLabel2.setHorizontalAlignment(SwingConstants.CENTER);
    22 jLabel2.setText("dictation path :");
    23 jPanel1.setLayout(gridLayout1);
    24 gridLayout1.setColumns(2);
    25 gridLayout1.setHgap(10);
    26 gridLayout1.setRows(2);
    27 contentPane.add(jScrollPane1, BorderLayout.CENTER);
    28 jScrollPane1.getViewport().add(jTextArea1, null);
    29 contentPane.add(jButton1, BorderLayout.SOUTH);
    30 contentPane.add(jPanel1, BorderLayout.NORTH);
    31 jPanel1.add(jLabel1, null);
    32 jPanel1.add(jTextField1, null);
    33 jPanel1.add(jLabel2, null);
    34 jPanel1.add(jTextField2, null);
    35 }

    5.编写JButton 组件的事件处理方法,当按钮按下时,完成解压或压缩。

    01 void jButton1_actionPerformed(ActionEvent e) {
    02 String sour = this.jTextField1.getText();
    03 String dest = this.jTextField2.getText();
    04 String sourExt=sour.substring(sour.length()-4,sour.length()).toLowerCase();
    05 String destExt=dest.substring(dest.length()-4,dest.length()).toLowerCase();
    06 //如果源文件是zip 文件,则此次进行的操作是解压
    07 if(sourExt.equals(".zip")){
    08 //显示解压的信息
    09 this.jTextArea1.append("\n"+"Unzip file " +" from "+this.jTextField1.getText()+
    10 " to "+this.jTextField2.getText()+"\n");
    11 //开始解压
    12 try{
    13 unzip();
    14 }catch(Exception err){
    15 err.printStackTrace();
    16 }
    17 }
    18 //如果目标文件是zip 格式,则此次操作是压缩
    19 if(destExt.equals(".zip")){
    20 //显示压缩信息
    21 this.jTextArea1.append("\n"+"Zip file "+this.jTextField1.getText()+
    22 " to "+this.jTextField2.getText()+"\n");
    23 //开始压缩
    24 try{
    25 zip();
    26 }catch(Exception err){
    27 err.printStackTrace();
    28 }
    29 }
    30 }

    6.编写文件解压方法unzip()。

    01 void unzip()throws Exception{
    02 byte[] buffer = new byte[1024]; //设置缓冲区
    03 File file = new File(this.jTextField2.getText()); //以解压文件将放置的目录路径创建一个File 对象
    04 //如果目录不存在,创建目录
    05 if (!file.exists())
    06 file.mkdirs();
    07 ZipEntry ze =null;
    08 ZipFile zf = new ZipFile(new File(this.jTextField1.getText())); //创建ZipFile 对象
    09 //获得其中的ZipEntry 对象
    10 Enumeration enum = zf.entries();
    11 if (enum.hasMoreElements()){
    12 ze = (ZipEntry)enum.nextElement();
    13 }
    14 //以最终解压文件的路径创建一个File 对象
    15 file = new File(this.jTextField2.getText()+File.separator+ze.getName());
    16 //文件不存在,则新建
    17 if (!file.exists()){
    18 file.createNewFile();
    19 }
    20 //链接各输入输出流
    21 InputStream is = zf.getInputStream(ze);
    22 DataInputStream dis = new DataInputStream(is);
    23 FileOutputStream fos = new FileOutputStream(file);
    24 DataOutputStream dos = new DataOutputStream(fos);
    25 this.jTextArea1.append("Starting unzip ......\n");//显示信息,要开始解压
    26 //开始解压
    27 int bytes;
    28 while((bytes=dis.read(buffer,0,buffer.length))!=-1){
    29 dos.write(buffer,0,bytes);
    30 }
    31 //关闭输入输出流
    32 dis.close();
    33 dos.close();
    34 //显示信息,解压成功
    35 this.jTextArea1.append("\t"+"unzipped "+ze.getName()+"\n");
    36 this.jTextArea1.append("Unzip complete.\n");
    37 }

    7.编写文件压缩方法zip()。

    01 void zip()throws Exception{
    02 byte[] buffer = new byte[1024];//创建缓冲区
    03 //建立要压缩文件的输入流
    04 File file = new File(this.jTextField1.getText());
    05 FileInputStream fis = new FileInputStream(file);
    06 DataInputStream dis = new DataInputStream(fis);
    07 File zipfile = new File(this.jTextField2.getText());//创建压缩文件的File 对象
    08 //如果压缩文件不存在,则判断压缩文件的上层目录是否存在,如不存在,新建各级目录,最后新建压缩文件。
    09 if (!zipfile.exists()){
    10 File zipdir = new File(zipfile.getParent());
    11 if (!zipdir.exists()){
    12 zipdir.mkdirs();
    13 }
    14 zipfile.createNewFile();
    15 }
    16 //建立压缩文件包中的压缩文件的输出流
    17 ZipEntry ze = new ZipEntry(file.getName());
    18 FileOutputStream fos = new FileOutputStream(zipfile);
    19 ZipOutputStream zos = new ZipOutputStream(fos);
    20 zos.setMethod(ZipOutputStream.DEFLATED);
    21 zos.putNextEntry(ze);
    22 DataOutputStream dos = new DataOutputStream(zos);
    23 //显示信息,要开始压缩
    24 this.jTextArea1.append("Starting zip ......\n");
    25 //开始压缩
    26 int bytes;
    27 while ((bytes=dis.read(buffer,0,buffer.length))!=-1){
    28 dos.write(buffer,0,bytes);
    29 }
    30 //关闭输入输出流
    31 dis.close();
    32 dos.close();
    33 //显示压缩成功信息
    34 this.jTextArea1.append("\t"+"Zipped"+this.jTextField1.getText()+"\n");
    35 this.jTextArea1.append("Zip complete.\n");
    36 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值