sclipse 压缩,解压缩文件的java代码

eclipse 步骤:

创建project,

创建package,

创建class

============================================================================

压缩1

============================================================================

package zip;

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

public class FileZip {
    public FileZip(){}  
    
    public static boolean fileToZip(String sourceFilePath,String zipFilePath,String fileName){  
        boolean flag = false;  
        File sourceFile = new File(sourceFilePath);  
        FileInputStream fis = null;  
        BufferedInputStream bis = null;  
        FileOutputStream fos = null;  
        ZipOutputStream zos = null;  
           
        if(sourceFile.exists() == false){  
            System.out.println("待压缩的文件目录:"+sourceFilePath+"不存在.");  
        }else{  
            try {  
                File zipFile = new File(zipFilePath + "/" + fileName +".zip");  
                if(zipFile.exists()){  
                    System.out.println(zipFilePath + "目录下存在名字为:" + fileName +".zip" +"打包文件.");  
                }else{  
                    File[] sourceFiles = sourceFile.listFiles();  
                    if(null == sourceFiles || sourceFiles.length<1){  
                        System.out.println("待压缩的文件目录:" + sourceFilePath + "里面不存在文件,无需压缩.");  
                    }else{  
                        fos = new FileOutputStream(zipFile);  
                        zos = new ZipOutputStream(new BufferedOutputStream(fos));  
                        byte[] bufs = new byte[1024*10];  
                        for(int i=0;i<sourceFiles.length;i++){  
                            //创建ZIP实体,并添加进压缩包  
                            ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());  
                            zos.putNextEntry(zipEntry);  
                            //读取待压缩的文件并写进压缩包里  
                            fis = new FileInputStream(sourceFiles[i]);  
                            bis = new BufferedInputStream(fis, 1024*10);  
                            int read = 0;  
                            while((read=bis.read(bufs, 0, 1024*10)) != -1){  
                                zos.write(bufs,0,read);  
                            }  
                        }  
                        flag = true;  
                    }  
                }  
            } catch (FileNotFoundException e) {  
                e.printStackTrace();  
                throw new RuntimeException(e);  
            } catch (IOException e) {  
                e.printStackTrace();  
                throw new RuntimeException(e);  
            } finally{  
                //关闭流  
                try {  
                    if(null != bis) bis.close();  
                    if(null != zos) zos.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                    throw new RuntimeException(e);  
                }  
            }  
        }  
        return flag;  
    }  
       
    public static void main(String[] args){  
        String sourceFilePath = "C:\\xx\\code\\java";  
        String zipFilePath = "C:\\xx";  
        String fileName = "HelloWorld.java";  
        boolean flag = FileZip.fileToZip(sourceFilePath, zipFilePath, fileName);  
        if(flag){  
            System.out.println("文件打包成功!");  
        }else{  
            System.out.println("文件打包失败!");  
        }  
    }  
       

}

============================================================================

压缩2

扫描二维码关注公众号,回复: 1871089 查看本文章

============================================================================

package zipfile;

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.ZipOutputStream;



public class NewZip {
     /**
     * 完成的结果文件--输出的压缩文件
     */
    File targetFile;

    public NewZip() {
    }

    public NewZip(File target) {
        targetFile = target;
        if (targetFile.exists())
            targetFile.delete();
    }

    /**
     * 压缩文件
     *
     * @param srcfile
     */
    public void zipFiles(File srcfile) {

        ZipOutputStream out = null;
        try {
            out = new ZipOutputStream(new FileOutputStream(targetFile));

            if (srcfile.isFile()) {
                zipFile(srcfile, out, "");
            } else {
                File[] list = srcfile.listFiles();
                for (int i = 0; i < list.length; i++) {
                    compress(list[i], out, "");
                }
            }

            System.out.println("finish");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null)
                    out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 压缩文件夹里的文件
     * 起初不知道是文件还是文件夹--- 统一调用该方法
     *
     * @param file
     * @param out
     * @param basedir
     */
    private void compress(File file, ZipOutputStream out, String basedir) {
        /* 判断是目录还是文件 */
        if (file.isDirectory()) {
            this.zipDirectory(file, out, basedir);
        } else {
            this.zipFile(file, out, basedir);
        }
    }

    /**
     * 压缩单个文件
     *
     * @param srcfile
     */
    public void zipFile(File srcfile, ZipOutputStream out, String basedir) {
        if (!srcfile.exists())
            return;
        //if the srcfile exists,continue to tar,
        //if not exists,return .

        byte[] buf = new byte[1024];
        FileInputStream in = null;

        try {
            int len;
            in = new FileInputStream(srcfile);
            out.putNextEntry(new ZipEntry(basedir + srcfile.getName()));

            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null)
                    out.closeEntry();
                if (in != null)
                    in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 压缩文件夹
     *
     * @param dir
     * @param out
     * @param basedir
     */
    public void zipDirectory(File dir, ZipOutputStream out, String basedir) {
        if (!dir.exists())
            return;

        File[] files = dir.listFiles();
        for (int i = 0; i < files.length; i++) {
            /* 递归 */
            compress(files[i], out, basedir + dir.getName() + "/");
        }
    }


    //测试
    public static void main(String[] args){
        File f = new File("C:\\xx\\code\\java");
        new NewZip(new File("C:\\xx", f.getName() + ".zip")).zipFiles(f);
    }

}


============================================================================

解压

============================================================================

package unzip;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class UZipFile {
    /**
       * 解压到指定目录
       */
      public static void unZipFiles(String zipPath,String descDir)throws IOException
      {
        unZipFiles(new File(zipPath), descDir);
      }
      /**
       * 解压文件到指定目录
       */
      @SuppressWarnings("rawtypes")
      public static void unZipFiles(File zipFile,String descDir)throws IOException
      {
        File pathFile = new File(descDir);
        if(!pathFile.exists())
        {
          pathFile.mkdirs();
        }
        //解决zip文件中有中文目录或者中文文件
        ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
        for(Enumeration entries = zip.entries(); entries.hasMoreElements();)
        {
          ZipEntry entry = (ZipEntry)entries.nextElement();
          String zipEntryName = entry.getName();
          InputStream in = zip.getInputStream(entry);
          String outPath = (descDir+zipEntryName).replaceAll("\\*", "\\");;
          //判断路径是否存在,不存在则创建文件路径
          File file = new File(outPath.substring(0, outPath.lastIndexOf('\\')));
          if(!file.exists())
          {
            file.mkdirs();
          }
          //判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
          if(new File(outPath).isDirectory())
          {
            continue;
          }
          //输出文件路径信息
          System.out.println(outPath);
          OutputStream out = new FileOutputStream(outPath);
          byte[] buf1 = new byte[1024];
          int len;
          while((len=in.read(buf1))>0)
          {
            out.write(buf1,0,len);
          }
          in.close();
          out.close();
        }
        System.out.println("******************解压完毕********************");
      }
      public static void main(String[] args) throws IOException {
        /**
         * 解压文件
         */
        File zipFile = new File("C:\\xx\\java.zip");
        String path = "C:\\xx\\JAVA\\";
        unZipFiles(zipFile, path);
      }
    }

参考 :https://www.jb51.net/article/127844.htm

======================================================================

结果:

C:\xx\JAVA\HelloWorld.class
C:\xx\JAVA\HelloWorld.java
******************解压完毕********************


猜你喜欢

转载自blog.csdn.net/qq_29649399/article/details/80908103