码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA UI 实现ZIP的压缩与解压缩

时间:2018-05-01 23:42:17      阅读:262      评论:0      收藏:0      [点我收藏+]

标签:RKE   open   leo   sts   ipo   .exe   xtend   tab   indexof   

压缩与解压缩代码

package ZIP;


import java.io.*;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
 
public class Zipun {
    public static void zip(String srcRootDir,File file,ZipOutputStream zos) throws Exception{
        if(file == null) return;
        if(file.isFile()){
            int count;
            //获取文件相对于压缩文件夹根目录的子路径
            String subPath = file.getAbsolutePath();
            int index = subPath.indexOf(srcRootDir);
            if(index != -1){
                subPath = subPath.substring(srcRootDir.length() + 1);
            }
            ZipEntry entry = new ZipEntry(subPath);
            zos.putNextEntry(entry);
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            while((count = bis.read())!=-1)
                zos.write(count);
            bis.close();
            zos.closeEntry();
        }
        else{
            File[] childFileList = file.listFiles();
            for(int i=0;i<childFileList.length;i++){
                childFileList[i].getAbsolutePath().indexOf(file.getAbsolutePath());
                zip(srcRootDir,childFileList[i],zos);
            }
        }
    }
    /**
     * zip程序入口
     * @param srcPath 源文件路径
     * @param zipPath 压缩文件的路径
     * @param zipFileName 压缩文件的名字
     * @throws Exception 抛出异常
     */
    public static void zip(String srcPath,String zipPath,String zipFileName) throws Exception{
        ZipOutputStream zos = null;
        try{
            File srcFile = new File(srcPath);
            /**
             * 防止无限递归
             */
            if(srcFile.isDirectory()&&zipPath.indexOf(srcPath) != -1){
                throw new Exception("无限递归");
            }
            /**
             * 判断压缩文件保存的路径是否存在,不存在,就创建
             */
            File zipDir = new File(zipPath);
            if(!zipDir.exists() || !zipDir.isDirectory()){
                zipDir.mkdirs();
            }
            //如果只是压缩一个文件,则需要截取该文件的父目录
            String srcRootDir = srcPath;
            if(srcFile.isFile()){
                int index = srcPath.lastIndexOf(File.separator);
                if(index != -1){
                    srcRootDir = srcPath.substring(0,index);
                }
            }
            /**
             * 调用递归的方法进行目录或文件的压缩
             */
            zos = new ZipOutputStream(new FileOutputStream(new File(zipPath+File.separator+zipFileName)));
            //System.out.println(srcDir);
            zip(srcRootDir,srcFile,zos);
            zos.flush();
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            if(zos != null) zos.close();
        }
    }
    /**
     * 解压缩zip包
     * @param zipFilePath zip文件的全路径
     * @param unzipFilePath 解压后的文件保存的路径
     * @param includeZipFileName 解压后的文件保存的路径是否包含压缩文件的文件名。true-包含;false-不包含
     */
    public static void unzip(String zipFilePath, String unzipFilePath) throws Exception
    {

        File zipFile = new File(zipFilePath);
        //创建解压缩文件保存的路径
        File unzipFileDir = new File(unzipFilePath);
        if (!unzipFileDir.exists() || !unzipFileDir.isDirectory())
        {
            unzipFileDir.mkdirs();
        }

        //开始解压
        ZipEntry entry = null;
        String entryFilePath = null, entryDirPath = null;
        File entryFile = null, entryDir = null;
        int index = 0, count = 0, bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        ZipFile zip = new ZipFile(zipFile);
        Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>)zip.entries();
        //循环对压缩包里的每一个文件进行解压
        while(entries.hasMoreElements())
        {
            entry = entries.nextElement();
            //构建压缩包中一个文件解压后保存的文件全路径
            entryFilePath = unzipFilePath + File.separator + entry.getName();
            //构建解压后保存的文件夹路径
            index = entryFilePath.lastIndexOf(File.separator);
            if (index != -1)
            {
                entryDirPath = entryFilePath.substring(0, index);
            }
            else
            {
                entryDirPath = "";
            }
            entryDir = new File(entryDirPath);
            //如果文件夹路径不存在,则创建文件夹
            if (!entryDir.exists() || !entryDir.isDirectory())
            {
                entryDir.mkdirs();
            }

            //创建解压文件
            entryFile = new File(entryFilePath);
            if (entryFile.exists())
            {
                //删除已存在的目标文件
                entryFile.delete();
            }

            //写入文件
            bos = new BufferedOutputStream(new FileOutputStream(entryFile));
            bis = new BufferedInputStream(zip.getInputStream(entry));
            while ((count = bis.read(buffer, 0, bufferSize)) != -1)
            {
                bos.write(buffer, 0, count);
            }
            bos.flush();
            bos.close();
        }
    }

}
UI 部分代码

package ZIP;

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 ZIP.Zipun;

public class ZipTest{  
   public static void main(String[] args){  
      EventQueue.invokeLater(new Runnable()  {  
            @Override
            public void run(){  
               ZipTestFrame frame = new ZipTestFrame();  
               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
               frame.setVisible(true);  
            }  
         });  
   }  
}  

    
class ZipTestFrame extends JFrame  {  
    
    public ZipTestFrame(){  
        setTitle("李华东 201501060709");  
        //窗口大小
        setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);  
 
        //创建菜单  
        JMenuBar menuBar = new JMenuBar();  
        JMenu menu1 = new JMenu("解压") ;  
        JMenu menu2 = new JMenu("压缩") ;  
        
        JMenuItem openItem = new JMenuItem("选择一个zip文件");  
        menu1.add(openItem);  
        openItem.addActionListener(new ActionListener(){  
            @Override
            public void actionPerformed(ActionEvent event){  
                //选择文件
               JFileChooser chooser = new JFileChooser();  
               chooser.setCurrentDirectory(new File("D:\\"));  
               //打开文件选择器对话框
               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(){  
            @Override
            public void actionPerformed(ActionEvent event){                  
                try {  
                    model.addElement("开始解压到文件所在目录") ;  
                    Zipun.unzip(zipname, zipname.substring(0, zipname.lastIndexOf(".")));
                    model.addElement("解压成功!") ;  
                } catch (Exception e) {  
                    model.addElement("解压错误!") ;  
                    e.printStackTrace();  
                }                      
            }  
         });  
        // 添加  
        JMenuItem addItem = new JMenuItem("添加要压缩的文件或文件夹");  
        menu2.add(addItem);  
        addItem.addActionListener(new ActionListener(){  
            @Override
            public void actionPerformed(ActionEvent event){    
                //选择文件
                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(){  
            @Override
            public void actionPerformed(ActionEvent event){  
                  try {  
                      Zipun.zip(addFilename,addFilename.substring(0, addFilename.lastIndexOf(File.separator)),new File(addFilename).getName()+".zip");
                    model.addElement("压缩成功!") ;  
                      
                 } catch (Exception e) {  
                    model.addElement("压缩错误!") ;  
                    e.printStackTrace();  
                }  
            }          
         });  
        
        //  exit  
        JMenuItem exitItem = new JMenuItem("退出");  
        menu1.add(exitItem);  
        exitItem.addActionListener(new ActionListener(){  
            @Override
            public void actionPerformed(ActionEvent event)  
            {  
               System.exit(0);  
            }  
         });  
        menuBar.add(menu1);  
        menuBar.add(menu2) ;  
        setJMenuBar(menuBar);  
 
        model = new DefaultListModel() ;  
        model.addElement("文件列表") ;  
          fileList = new JList(model);  
          add(new JScrollPane(fileList), BorderLayout.CENTER);  
    }  
 
    //显示文件列表
    public void scanZipFile(){  
       model.removeAllElements() ;  
       new SwingWorker<Void, String>(){  
            @Override
            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;  
            }
            @Override
            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("到当前目录下的 "+new File(addFilename).getName()+".zip 文件下") ;         
    }  
    /**
     * 设置宽度和长度
     * 自适应当前屏幕的大小
     */
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();     
    public  final int DEFAULT_WIDTH = (int)screenSize.getWidth()/2;  
    public  final int DEFAULT_HEIGHT = (int)screenSize.getHeight()/2;  
     
    private JList fileList;  
    private String zipname;  
    private String addFilename ;  
    DefaultListModel model ;  
     
}

JAVA UI 实现ZIP的压缩与解压缩

标签:RKE   open   leo   sts   ipo   .exe   xtend   tab   indexof   

原文地址:https://www.cnblogs.com/1iHu4D0n9/p/8977454.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!