`
chuanheng
  • 浏览: 15192 次
  • 性别: Icon_minigender_1
  • 来自: 成都
最近访客 更多访客>>
社区版块
存档分类
最新评论

java以zip格式实现压缩解压,有界面

阅读更多

压缩

package Util;

import java.io.BufferedInputStream;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.util.zip.CRC32;  
import java.util.zip.CheckedOutputStream;  
import java.util.zip.ZipEntry;  
import java.util.zip.ZipOutputStream;  

public class ZipUtils {  
  
    public static final String EXT = ".zip";  
    private static final String BASE_DIR = "";  
  
    // 符号"/"用来作为目录标识判断符  
    private static final String PATH = "/";  
    private static final int BUFFER = 1024;  
  
    /** 
     * 压缩 
     * @param srcFile 
     * @throws Exception 
     */  
    public static void compress(File srcFile) throws Exception {  
        String name = srcFile.getName();  
        String basePath = "D:\\"  ;
        String destPath = basePath + name + EXT;  
        compress(srcFile, destPath);  
    }  
  
    /** 
     * 压缩 
     *  
     * @param srcFile 
     *            源路径 
     * @param destPath 
     *            目标路径 
     * @throws Exception 
     */  
    public static void compress(File srcFile, File destFile) throws Exception {  
  
        // 对输出文件做CRC32校验  
        CheckedOutputStream cos = new CheckedOutputStream(new FileOutputStream(  
                destFile), new CRC32());  
  
        ZipOutputStream zos = new ZipOutputStream(cos);  
  
        compress(srcFile, zos, BASE_DIR);  
  
        zos.flush();  
        zos.close();  
    }  
  
    /** 
     * 压缩文件 
     *  
     * @param srcFile 
     * @param destPath 
     * @throws Exception 
     */  
    public static void compress(File srcFile, String destPath) throws Exception {  
        compress(srcFile, new File(destPath));  
    }  
  
    /** 
     * 压缩 
     *  
     * @param srcFile 
     *            源路径 
     * @param zos 
     *            ZipOutputStream 
     * @param basePath 
     *            压缩包内相对路径 
     * @throws Exception 
     */  
    private static void compress(File srcFile, ZipOutputStream zos,  
            String basePath) throws Exception {  
        if (srcFile.isDirectory()) {  
            compressDir(srcFile, zos, basePath);  
        } else {  
            compressFile(srcFile, zos, basePath);  
        }  
    }  
  
    /** 
     * 压缩 
     *  
     * @param srcPath 
     * @throws Exception 
     */  
    public static void compress(String srcPath) throws Exception {  
        File srcFile = new File(srcPath);  
  
        compress(srcFile);  
    }  
  
    /** 
     * 文件压缩 
     *  
     * @param srcPath 
     *            源文件路径 
     * @param destPath 
     *            目标文件路径 
     *  
     */  
    public static void compress(String srcPath, String destPath)  
            throws Exception {  
        File srcFile = new File(srcPath);  
  
        compress(srcFile, destPath);  
    }  
  
    /** 
     * 压缩目录 
     *  
     * @param dir 
     * @param zos 
     * @param basePath 
     * @throws Exception 
     */  
    private static void compressDir(File dir, ZipOutputStream zos,  
            String basePath) throws Exception {  
  
        File[] files = dir.listFiles();  
  
        // 构建空目录  
        if (files.length < 1) {  
            ZipEntry entry = new ZipEntry(basePath + dir.getName() + PATH);  
  
            zos.putNextEntry(entry);  
            zos.closeEntry();  
        }  
  
        for (File file : files) {  
  
            // 递归压缩  
            compress(file, zos, basePath + dir.getName() + PATH);  
  
        }  
    }  
  
    /** 
     * 文件压缩 
     *  
     * @param file 
     *            待压缩文件 
     * @param zos 
     *            ZipOutputStream 
     * @param dir 
     *            压缩文件中的当前路径 
     * @throws Exception 
     */  
    private static void compressFile(File file, ZipOutputStream zos, String dir)  
            throws Exception {  
  
        /** 
         * 压缩包内文件名定义 
         *  
         * <pre> 
         * 如果有多级目录,那么这里就需要给出包含目录的文件名 
         * 如果用WinRAR打开压缩包,中文名将显示为乱码 
         * </pre> 
         */  
        ZipEntry entry = new ZipEntry(dir + file.getName());  
  
        zos.putNextEntry(entry);  
  
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(  
                file));  
  
        int count;  
        byte data[] = new byte[BUFFER];  
        while ((count = bis.read(data, 0, BUFFER)) != -1) {  
            zos.write(data, 0, count);  
        }  
        bis.close();  
  
        zos.closeEntry();  
    }  
  
}  

 解压工具类

package Util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class UnZipUtils {

    public static void main(String[] args) throws IOException {

        unzip("D:\\test\\test.zip");

    }

 

   //-----------------------------------------方法一------------------------------------------------------------  

    /**

     * 采用 <code>ZipInputStream<code>读Zip文件的方式

     * 解压到当前目录

     * @param zipFilePath 需要解压的文件的路径

     * @throws IOException 

     */

    public static void unzip(String zipFilePath) throws IOException {
    	
    	File zipFile = new File(zipFilePath);
    		
    	String zipFileName = zipFile.getName();
        	
        String rootFileName = zipFile.getParentFile().getPath() + "/" + zipFileName.substring(0, zipFileName.lastIndexOf("."));
        	
        unzip(zipFilePath, rootFileName);
    	
    }

 

    /**

     * 采用 <code>ZipInputStream<code>读Zip文件的方式

     * 解压到指定目录

     * @param zipFilePath 需要解压的文件的路径

     * @param unzipFilePath 解压后文件的路径

     * @throws IOException

     */

    public static void unzip(String zipFilePath, String unzipFilePath) throws IOException {

        File rootFile = new File(unzipFilePath);

        rootFile.mkdirs();

 

        ZipInputStream input = new ZipInputStream(

                new BufferedInputStream(new  FileInputStream(zipFilePath)));

        ZipEntry entry = null;

 

        //Zip文件将里面的每个文件都作为一个ZipEntry, 父目录和子文件为两个单独的entry

        while((entry = input.getNextEntry()) != null) {

            File tmpFile = new File(unzipFilePath + "/" + entry.getName());

            tmpFile.getParentFile().mkdirs();

 

            if(entry.isDirectory()) {

                tmpFile.mkdir();

            }

            else {

                BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(tmpFile));

                byte[] datas = new byte[2048];

                int count;

                while((count = input.read(datas)) != -1) {

                    output.write(datas, 0, count);

                }

                output.close();

            }

 

            input.closeEntry();

        }

 

        input.close();

    }}

 界面类

package main;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.List;
import java.util.zip.*;
import javax.swing.*;

import Util.UnZipUtils;
import Util.ZipUtils;

/**
 * @version 1.00 2011-11-20
 * @author Wang Chuanheng
 */
public class ZipTest
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(new Runnable()
         {
            public void run()
            {
               ZipTestFrame frame = new ZipTestFrame();
               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               frame.setVisible(true);
            }
         });
   }
}

/**
 * A frame with a text area to show the contents of a file inside a ZIP archive, a combo box to
 * select different files in the archive, and a menu to load a new archive.
 */
class ZipTestFrame extends JFrame
{
   public ZipTestFrame()
   {
      setTitle("不支持中文解压!author: 王传恒2009110336");
      setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

      // add the menu and the Open and Exit menu items
      JMenuBar menuBar = new JMenuBar();
      JMenu menu1 = new JMenu("解压") ;
      JMenu menu2 = new JMenu("压缩") ;
      
      JMenuItem openItem = new JMenuItem("选择一个zip文件");
      menu1.add(openItem);
      openItem.addActionListener(new ActionListener()
         {
            public void actionPerformed(ActionEvent event)
            {
               JFileChooser chooser = new JFileChooser();
               chooser.setCurrentDirectory(new File("."));
               int r = chooser.showOpenDialog(ZipTestFrame.this);
               if (r == JFileChooser.APPROVE_OPTION)
               {
            	   zipname = chooser.getSelectedFile().getPath();
                  
                  scanZipFile();
               }
            }
         });
    //开始解压
      JMenuItem jieyaItem = new JMenuItem("开始解压");
      menu1.add(jieyaItem);
      jieyaItem.addActionListener(new ActionListener()
         {
            public void actionPerformed(ActionEvent event)
            {
            	
            	try {
            		model.addElement("开始解压到文件所在目录") ;
            		UnZipUtils.unzip(zipname) ;
            		model.addElement("解压成功!") ;
                } catch (IOException e) {
                	model.addElement("解压error,不支持中文") ;
                	e.printStackTrace();
                }
                  
            }
         });
      // 添加
      JMenuItem addItem = new JMenuItem("添加要压缩的文件或文件夹");
      menu2.add(addItem);
      addItem.addActionListener(new ActionListener()
         {
            public void actionPerformed(ActionEvent event)
            {
            	
            	//addFile() ;  
            	JFileChooser chooser = new JFileChooser();
               chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES) ;
               chooser.setCurrentDirectory(new File("D://"));
               int r = chooser.showOpenDialog(ZipTestFrame.this);
               if (r == JFileChooser.APPROVE_OPTION)
               {
                  addFilename = chooser.getSelectedFile().getPath();
                  addFile() ;

                  System.out.println(addFilename) ;
               }
            }
         });
      
   // 压缩选定文件
      JMenuItem zipItem = new JMenuItem("开始压缩");
      menu2.add(zipItem);
      zipItem.addActionListener(new ActionListener()
         {
            public void actionPerformed(ActionEvent event)
            {
                  try {
                	  
					ZipUtils.compress(addFilename) ;
					model.addElement("压缩成功!") ;
					
				} catch (Exception e) {
					model.addElement("压缩error,不支持中文") ;
					//System.out.println("压缩error!") ;
					e.printStackTrace();
				}
            }
               
         });
      
      //  exit
      JMenuItem exitItem = new JMenuItem("退出");
      menu1.add(exitItem);
      exitItem.addActionListener(new ActionListener()
         {
            public void actionPerformed(ActionEvent event)
            {
               System.exit(0);
            }
         });

      menuBar.add(menu1);
      menuBar.add(menu2) ;
      setJMenuBar(menuBar);

      // add the text area and combo box
      model = new DefaultListModel() ;
      model.addElement("文件列表") ;
      fileList = new JList(model);
      //fileList.setVisibleRowCount(12) ;
      add(new JScrollPane(fileList), BorderLayout.CENTER);
   }

   /**
    * Scans the contents of the ZIP archive and populates the combo box.
    */
   public void scanZipFile()
   {
	   model.removeAllElements() ;
      new SwingWorker<Void, String>()
         {
            protected Void doInBackground() throws Exception
            {
               ZipInputStream zin = new ZipInputStream(new FileInputStream(zipname));
               ZipEntry entry;
               while ((entry = zin.getNextEntry()) != null)
               {
                  publish(entry.getName());
                  zin.closeEntry();
               }
               zin.close();
               return null;
            }

            protected void process(List<String> names)
            {
            	
               for (String name : names)
                  model.addElement(name) ;
            
                  
            }
         }.execute();
   }
   
   
   public void addFile(){
	   System.out.println("addFile()") ;
	   model.removeAllElements() ;
	   
	   model.addElement("准备压缩: "+addFilename) ;
	   model.addElement("到     D:\\ ") ;
	   
   }
   
   public static final int DEFAULT_WIDTH = 800;
   public static final int DEFAULT_HEIGHT = 600;
   
   private JList fileList;
   private String zipname;
   private String addFilename ;
   DefaultListModel model ;
   
}
 

 

 

0
1
分享到:
评论
1 楼 foolishdault 2011-11-20  
这个对中文支持不够好,还是使用apache的实现比较好

相关推荐

    java版zip压缩解压代码

    `java版zip压缩解压代码`提供了在命令行环境中实现这一功能的程序。这个程序主要利用了Java的内置库,尤其是`java.util.zip`包中的类,如`ZipOutputStream`和`ZipInputStream`,来实现对文件和文件夹的ZIP压缩与解压...

    利用Java实现zip压缩解压缩

    ### Java 实现 ZIP 文件压缩与解压缩 #### 知识点概述 在现代软件开发过程中,数据压缩是一项非常重要的技术,特别是在处理大量数据时。Java 作为一种广泛应用的编程语言,提供了丰富的 API 来支持文件的压缩与解...

    ZIP格式压缩/解压系统设计(JAVA)

    通过设计,允许创建ZIP压缩文件,并对ZIP压缩文件中包含的文件进行显示、添加、解压、删除等操作。GUI界面与下图类似: 【实验目的】 要求学生能熟练使用基于Swing的GUI设计,熟练使用常用组件和容器,理解java事件...

    文件的ZIP格式压缩和解压

    在提供的"src"文件名列表中,可能包含的是用于实现ZIP压缩和解压功能的源代码。这些代码可能使用了某种编程语言(如C++、Python或Java),并封装了对ZIP文件格式的处理逻辑,包括读写ZIP文件头部信息、执行DEFLATE...

    Zip文件压缩和解压

    以上就是关于Zip文件压缩和解压的基本介绍,无论是通过图形界面工具还是编程实现,都能有效地管理和处理Zip文件。在实际应用中,我们还可以根据需求选择合适的压缩算法、设置密码保护、添加注释等功能,提高文件管理...

    JAVA实现的文件压缩

    在Java中,我们可以使用内置的`java.util.zip`包来处理ZIP格式的压缩和解压。这个包提供了`ZipOutputStream`和`ZipInputStream`类,分别用于创建和读取ZIP文件。 4. **使用ZipOutputStream** - 初始化:首先,我们...

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

    对于压缩文件,Java提供了一个内置的库——`java.util.zip`,它包含了一系列用于处理ZIP格式压缩文件的类,如`ZipInputStream`和`ZipOutputStream`,它们分别用于读取和写入ZIP文件。 在解压缩部分,我们可以创建一...

    ZIP格式的文件压缩程序的设计与实现

    编写一个Java图形用户界面程序,可以打开一个对话框选择1个或多个文件进行压缩,压缩后的文件为ZIP格式,也可以选择ZIP压缩文件将其解压。在压缩文件时可以选择将文件分割成几份压缩包文件,同样解压缩时可以选择多...

    基于Java的开源Winzip压缩工具Java版源码.zip

    这个“基于Java的开源Winzip压缩工具Java版源码.zip”文件提供了一个用Java实现的开源Winzip压缩工具的源代码。通过对这份源码的学习和分析,我们可以深入理解Java在文件压缩领域的应用,以及如何利用Java API来实现...

    linux、window通用文件解压

    在Linux和Windows之间实现通用解压,通常意味着我们需要使用一种在两个平台上都广泛支持的压缩格式,如ZIP或7z。ZIP是最常见的格式,它在Windows上可以通过内置的资源管理器直接解压,而在Linux上,可以使用`unzip`...

    基于java的开源Winzip压缩工具Java版源码.zip

    2. **Java.util.zip**: 这是Java提供的标准压缩库,包含了GZIPOutputStream和ZipOutputStream等类,用于实现GZIP和ZIP格式的压缩。ZipOutputStream允许我们创建ZIP档案,添加多个条目(entries),每个条目可以是...

    JAVA 从压缩包中提取文件

    本项目旨在演示如何使用Java编程语言从ZIP格式的压缩文件中提取文件并显示其名称。ZIP是一种广泛使用的文件压缩与存档格式,常用于数据备份和网络传输中。在实际应用中,能够灵活处理ZIP文件对于开发人员来说是一项...

    功能最齐全的JAVA压缩软件

    如果"javazip"是软件的名称,那么它可能是一个扩展了这些基础功能的第三方库,提供了更强大的API和界面。 总的来说,这个Java压缩软件可能是一个开源项目,集成了各种压缩算法,包括但不限于ZIP、GZIP、TAR等常见...

    基于Java的实例源码-开源Winzip压缩工具Java版源码.zip

    此外,可能还会涉及多线程技术,以实现并行压缩,提高压缩速度。Java的并发API,如ExecutorService和Future,可以有效地管理和控制并发任务。 在实际项目中,为了实现文件的选取、界面交互和用户反馈等功能,开发者...

    WinRar的RAR格式一般要比其他的ZIP格式有更高的压缩率,尤其他还提供了可选择的、针对多媒体数据的压缩算法

    但WinRAR就不同了,不但能解压多数压缩格式,且不需外挂程序支持就可直接建立 ZIP 格式的压缩文件,所以我们不必担心离开了其他软件如何处理 ZIP 格式的问题。  4、设置项目非常完善,并且可以定制界面  通过...

    Java zip压缩包查看程序源码.rar

    `Java zip压缩包查看程序源码.rar`是一个包含Swing图形界面应用程序和相关工具类的资源包,它允许开发者查看和操作ZIP压缩文件。这个工具包简化了与ZIP文件交互的过程,减少了开发者的编码工作量。 首先,Swing是...

    7-zip打包工具

    - **支持多种格式**:除了自己的7z格式,7-Zip还支持ZIP、GZIP、BZIP2、TAR、CAB、ISO、ARJ、RAR等多种常见压缩格式,并能读取和解压更多其他格式。 - **界面友好**:提供图形用户界面(GUI)和命令行接口(CLI)...

    java课程设计之批量压缩文件

    接着,我们看到一个名为`ZipUtil.java`的类,这很可能是自定义的Java工具类,用于实现文件的压缩和解压功能。在`ZipUtil`中,可能会包含如`compressFile`和`unzipFile`这样的方法,分别用于单个文件的压缩和解压,...

    开源包7zip压缩工具的编译及使用

    7-Zip是一款强大的开源压缩工具,它以其高效率和广泛支持的压缩格式而闻名。这款软件不仅提供了图形用户界面,还支持命令行模式,使得它在各种环境下都能灵活使用。以下将详细介绍7-Zip的编译过程以及如何利用其进行...

    Java毕业设计-JAVA文件压缩与解压缩实践(源代码+论文).rar

    内容聚焦于Java文件压缩与解压缩功能的实现,采用高效、便捷的算法,支持多种常见的文件格式。项目结构清晰,注释充分,易于理解和二次开发。 主要功能特点: 1. 支持主流压缩格式:如ZIP、RAR、7z等。 2. 文件...

Global site tag (gtag.js) - Google Analytics