对zip文件进行解压操作和对一个文件进行压缩操作

注意这里用的是apche下的zip

package org.springframework.validation;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.Enumeration;

/**
 * @author qinlinsen
 */
public class ZipFileUtils {
    private static final String ZIP_FILE_NOT_EXISTS = "zip file doesn‘t exists";
    private static final String DEFAULT_ZIP_CHARSET = "GBK";
    private static final String UNZIP_OPERATION_SUCCESS = "doUnzip operation success ";
    private static final String UNZIP_FILE_PATH_CANNOT_BE_NULL = "unzip file absolute path cannot be null";
    private static final String ZIP_FILE_PATH_CANNOT_BE_NULL = "zip file absolute path cannot be null";
    private static final String FILE_SEPARATOR = "file.separator";

    /**
     * 解压操作
     * @param zipFilePath    zip文件的绝对路径
     * @param unzipFilePath  解压之后文件的绝对路径
     * @return
     */
    public static String doUnzip(String zipFilePath, String unzipFilePath) {
        //validate input parameters
        Assert.notNull(unzipFilePath, UNZIP_FILE_PATH_CANNOT_BE_NULL);
        Assert.notNull(zipFilePath, ZIP_FILE_PATH_CANNOT_BE_NULL);
        ZipFile zipFile = null;
        String directoryName = "";
        try {
            zipFile = new ZipFile(zipFilePath, DEFAULT_ZIP_CHARSET);
        } catch (IOException e) {
            System.out.println(ZIP_FILE_NOT_EXISTS);
            e.printStackTrace();
        }
        Enumeration<ZipEntry> entries = zipFile.getEntries();
        while (entries.hasMoreElements()) {
            ZipEntry zipEntry = entries.nextElement();
            if (zipEntry.isDirectory()) {
                directoryName = zipEntry.getName();
                directoryName = directoryName.substring(0, directoryName.length() - 1);
                if(!unzipFilePath.endsWith(System.getProperty(FILE_SEPARATOR))){
                    unzipFilePath=unzipFilePath+System.getProperty(FILE_SEPARATOR);
                }
                File folder = new File(unzipFilePath + directoryName);

                //create a folder
                folder.mkdir();
            } else {
                InputStream in = null;
                OutputStream out = null;
                try {
                    File file = new File(unzipFilePath + zipEntry.getName());
                    //create a parent file
                    file.getParentFile().mkdir();
                    //create a file
                    file.createNewFile();
                    //read and write operation
                    in = zipFile.getInputStream(zipEntry);
                    out = new FileOutputStream(file);
                    int len = 0;
                    byte[] bytes = new byte[1024];
                    while ((len = in.read(bytes, 0, 1024)) != -1) {
                        out.write(bytes, 0, len);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        in.close();
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        System.out.println(UNZIP_OPERATION_SUCCESS);
        if (!StringUtils.isEmpty(zipFile)) {
            try {
                zipFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return unzipFilePath + directoryName;
    }

    /**
     * 压缩文件的操作
     *具体用法参考下面的main方法的用法
     * @param sourceUnzipFileAbsolutePath  要压缩的文件的绝对路径,这里假定这个文件形如:a/b/c/d.jpg
     * @param destZipFileAbsolutePath  压缩文件的绝对路径
     */
    public static void doZip(String sourceUnzipFileAbsolutePath, String destZipFileAbsolutePath) {

        File unzipFile = null;
        BufferedInputStream in = null;
        ZipOutputStream out = null;
        try {
            //validate input parameters
            Assert.notNull(sourceUnzipFileAbsolutePath, UNZIP_FILE_PATH_CANNOT_BE_NULL);
            Assert.notNull(destZipFileAbsolutePath, ZIP_FILE_PATH_CANNOT_BE_NULL);
            Assert.isTrue(destZipFileAbsolutePath.endsWith(".zip"), "zip file must ends with .zip");
            unzipFile = new File(sourceUnzipFileAbsolutePath);
            if (unzipFile.exists()) {
                File zipFile = new File(destZipFileAbsolutePath);
                if (zipFile.exists()) {
                    throw new RuntimeException("该zip文件已经存在,请重新输入.zip文件的绝对路径");
                }
                zipFile.createNewFile();

                if (zipFile.exists()) {
                    File[] sourceFiles = unzipFile.listFiles();
                    if (null == sourceFiles || sourceFiles.length < 1) {
                        System.out.println("File Catalog:" + sourceUnzipFileAbsolutePath + "nothing in there,don‘t have to compress!");
                    } else {
                        out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
                        byte[] buffers = new byte[1024 * 10];
                        for (int i = 0; i < sourceFiles.length; i++) {
                            // create .zip and put pictures in
                            ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
                            out.putNextEntry(zipEntry);
                            // read documents and put them in the zip
                            in = new BufferedInputStream(new FileInputStream(sourceFiles[i]), 1024 * 10);
                            int read = 0;
                            while ((read = in.read(buffers, 0, buffers.length)) != -1) {
                                out.write(buffers, 0, read);
                            }
                        }
                        System.out.println("压缩成功,压缩文件的目录:" + zipFile.getAbsolutePath());
                    }
                }
            } else {
                System.out.println(unzipFile.getAbsolutePath() + " doesn‘t not exists !");
                throw new RuntimeException(unzipFile.getAbsolutePath() + " doesn‘t not exists !");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        } finally {
            try {
                if (null != in) {
                    in.close();
                }
                if (null != out) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *对jpg照片进行重命名操作
     * @param unzipFilePath  需要重命名的文件路径
     * @param userName 用户名
     * @param workCode 工号
     * @param orgCode   结构代码
     */
    public static void doRename(String unzipFilePath,String userName,String workCode,String orgCode){
        try {
            Assert.notNull(unzipFilePath,"file cannot be null");
            Assert.notNull(userName,"user name  cannot be null");
            Assert.notNull(workCode,"work code cannot be null");
            Assert.notNull(orgCode,"organization code  cannot be null");
            File unzipFile = new File(unzipFilePath);
            File[] files = unzipFile.listFiles();
            int count=0;
            for(File file :files){
                String destFilePath = file.getParent()+"/";
                String destFileName=userName+count+"-"+workCode+count+"-"+orgCode+".jpg";
                file.renameTo(new File(destFilePath+destFileName));
                count++;
            }
            System.out.println("rename successfully !");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("rename failed !");
        } finally {
        }
    }
    public static void main(String[] args) {
        //压缩文件的操作测试
        String zipPath_zip_operation = "C:\\Users\\yckj0911\\Desktop\\yyyy.zip";
        String unzipPath_zip_operation = "C:\\Users\\yckj0911\\Desktop\\人民2\\人民";
//        doZip(unzipPath_zip_operation, zipPath_zip_operation);

        //解压文件的操作测试:
        String zipPath_unzip_operation = "C:\\Users\\yckj0911\\Desktop\\yyyy.zip";
        String unzipPath_unzip_operation = "C:\\Users\\yckj0911\\Desktop\\ccc";
        if(!unzipPath_unzip_operation.endsWith(System.getProperty("file.separator"))){
            unzipPath_unzip_operation=unzipPath_unzip_operation+System.getProperty("file.separator");
        }
      //doUnzip(zipPath_unzip_operation,unzipPath_unzip_operation);
      String need_rename_file_path= "C:\\Users\\yckj0911\\Desktop\\ccc";
      doRename(need_rename_file_path,"qls","yckj","YCKJ");
    }
}

原文地址:https://www.cnblogs.com/1540340840qls/p/9722985.html

时间: 2024-08-29 10:29:54

对zip文件进行解压操作和对一个文件进行压缩操作的相关文章

windows phone使用sharpcompress进行解压压缩文件

在做移动端时,当我们需要从服务器获得多个文件时,为了节约流量,服务器一般会返回一个压缩包,那我们就是下载完成后,在手机中进行解压到指定位置 SharpCompress就是可以在手机中进行解压一个类库(.net),在codeplex是开源,支持桌面端和移动端 点击下载最新版本       查看支持内容      API使用示例 下面我们看一下在windows phone中使用其进行解压ZIP包 public async void DownloadAndUnCompress() { string s

PHP文件操作 之往一个文件写入数据

//打开一个文件 $f = fopen($filename,'wb'); $filename:打开一个文件,不存在则自动创建,如果不能创建,说明指定的文件目录有错误 wb:写入的方式 ---- 覆盖原内容ab:追加的方式 ---- 往文件尾部追加数据 if(!$f) { die("打开文件失败"); } else { echo '打开文件成功'."<br/>"; } //判断文件是否可写 if(!is_writable($f)) { die("

dos移动一个文件内的所有内容到另一个文件

1)移动一个文件内的所有内容到另一个文件(不包含该目录) 比如:把文件夹1 里面的所有文件(包含子目录)全部移动到与1同级目录的文件夹2中: cd 1 for /f "tokens=* delims= " %a in ('dir /a /b') do (move %a ..\2)

读取两文件,不同的内容存入另一个文件中

<?php /** * 从两个.csv 文件中读出数据 * 比较这两个文件不同的数据,并存入.csv 文件中 */ class Readfiledata { private function __construct() { } /** * 读文件并获取数据 */ private static function getdata($file) { $handle = fopen ( $file, 'r' ); $orderform = array (); $i=0; while ( false !=

PHP文件操作 之读取一个文件(以二进制只读的方式打开)

最近应用了文件的读取,顺便复习一下! //读取一个文件 $f = fopen($filename,'rb'); $f: 表示返回的一个资源句柄 $filename:要打开的文件路径 rb:参数,表示只读且以二进制的形式打开该文件 读取后循环该文件数据,因为读取文件是一行一行的 //如果没有读取到文件结束则循环 while(!feof($f)) { $str = fgets($f);//获取的是每一行的数据 /*对该数据进行的操作代码...*/ } //关闭该资源 fclose($f);

java中的文件读取和文件写出:如何从一个文件中获取内容以及如何向一个文件中写入内容

1 2 3 import java.io.BufferedReader; 4 import java.io.BufferedWriter; 5 import java.io.File; 6 import java.io.FileInputStream; 7 import java.io.FileNotFoundException; 8 import java.io.FileOutputStream; 9 import java.io.IOException; 10 import java.io.

读取两文件,不同的内容存入还有一个文件里

<?php /** * 从两个.csv 文件里读出数据 * 比較这两个文件不同的数据.并存入.csv 文件里 */ header("Content-type:text/html;charset=utf-8"); class Readfiledata { /** * 链接数据库 */ private static function connect(){ require_once 'index2.php'; mysql_connect('localhost','root','');

C#文件操作之把一个文件复制到另外一个文件夹下

一.文件复制例子如下,具体情况,根据需求扩展. /// <summary> /// /// </summary> /// <param name="srcFolder">源目录</param> /// <param name="destFolder">目标目录</param> /// <param name="filename">源文件名</param>

java 把一个文件夹里图片复制到另一个文件夹里

import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Calendar; public class SendServer { private int num = 0; public void process() { Calendar calendar = Calendar.getInstance(); String dir = calendar.