我的第一个压缩解压java小程序hello zip

Hello Zip

暂时只有五个函数,其中两个为重载。
参数都是绝对路径,采用ZipInputStream和BufferedInputStream
可以递归,可以作用于文件夹压缩解压
可以设置解压或者压缩的目的路径(第二个参数)

import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class MyZipAndUnzip
{
    /** @author crimson
     * @version v0.1
     * 有五个public方法,前四个函数参数均为绝对路径String,第五个方法设置缓冲区大小*/
    public static void main(String[] args)
    {

        System.out.println("start to zip");
        try
        {
            MyZipAndUnzip.zip("C:\\Users\\woshi\\Desktop\\javadoc");
            MyZipAndUnzip.unZip("C:\\Users\\woshi\\Desktop\\javadoc.zip",
                    "C:\\Users\\woshi\\Desktop\\test");
        }catch(IOException e)
        {
            e.printStackTrace();
        }
    }
    private static Path baseDir;
    /** default BUFFER_SIZE is 50,you can change it by using setBufferSize(int)::void*/
    private static int BUFFER_SIZE = 50;
    private static byte[] buffer = new byte[BUFFER_SIZE];
    private MyZipAndUnzip(){}

    /** @param fileToUnzip The path of a file you want to unzip
     *                    The default dest dir is the same dir of the file  to unzip
     * @throws IOException 可能会报文件未找到或非文件错误,或者目的路径不正确等错误*/
    public static void unZip(String fileToUnzip) throws IOException
    {
        File file = new File(fileToUnzip);
        unZip(fileToUnzip, file.getParent());
    }

    /** @param fileToUnzip The path of a file you want to unzip
     * @param destDir     The path you want to place new the Zip file to*/
    public static void unZip(String fileToUnzip, String destDir) throws IOException
    {
        File file = new File(fileToUnzip);
        if (file.isDirectory() || !file.exists()) throw new IOException("zipfile chosed error");
        baseDir = Paths.get(destDir);
        if (baseDir.toFile().isFile()) throw new IOException("path error,this is not a correct path");
        ZipInputStream in = new ZipInputStream(new BufferedInputStream(new FileInputStream(file)));
        unZipImpl(in, baseDir);
        in.close();
    }

    public static void zip(String fileOrDirToZip) throws IOException
    {
        File file = new File(fileOrDirToZip);
        zip(fileOrDirToZip, file.getParent());
    }

    /** @param fileOrDirToZip The path of a file or dir you want to zip
     * @param destDir        The path you want to place new the Zip file to*/
    public static void zip(String fileOrDirToZip, String destDir) throws IOException
    {
        File file = new File(fileOrDirToZip);
        if (!file.exists()) throw new IOException("file to zip does not exist!");
        baseDir = Paths.get(destDir);
        if (baseDir.toFile().isFile()) throw new IOException("path error,not a correct path!");
        File newFileZip = new File(baseDir.resolve(fileOrDirToZip + ".zip").toString());
        if (!file.exists()) throw new FileNotFoundException();
        newFileZip = solveDuplicatedName(fileOrDirToZip, newFileZip);
        newFileZip.createNewFile();
        ZipOutputStream out = new ZipOutputStream
                (new BufferedOutputStream(new FileOutputStream(newFileZip)));
        zipImpl(file, out);
        out.close();
    }

    public static void setBufferSize(int customBufferSize)
    {
        MyZipAndUnzip.BUFFER_SIZE = customBufferSize;
    }

    private static void unZipImpl(ZipInputStream in, Path baseDir) throws IOException
    {
        ZipEntry zipEntry = null;
        while ((zipEntry = in.getNextEntry()) != null)
        {
            File file = new File(baseDir.resolve(zipEntry.getName()).normalize().toString());
            createFile(file);
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
            int size = 0;
            while ((size = in.read(buffer, 0, BUFFER_SIZE)) != -1)
            {
                out.write(buffer, 0, size);
            }
            out.close();
        }
    }

    private static void createFile(File file) throws IOException
    {
        if (file.getParentFile().exists())
        {
            if (file.exists()) return;
            file.createNewFile();
        } else
        {
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
    }

    private static File solveDuplicatedName(String fileOrDirToUnzip, File zipFileToCreate)
    {
        if (!zipFileToCreate.exists()) return zipFileToCreate;
        File temp = zipFileToCreate;
        int icopy = 1;
        while (temp.exists())
        {

            temp = new File(baseDir.resolve(fileOrDirToUnzip + "(" + icopy + ")" + ".zip").toString());
            icopy++;
        }
        return temp;

    }


    private static void zipImpl(File file, ZipOutputStream out) throws IOException
    {
        if (!file.isDirectory())
        {
            out.putNextEntry(new ZipEntry
                    (baseDir.relativize(Paths.get(file.getAbsolutePath())).normalize().toString()));
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
            int size = 0;
            while ((size = in.read(buffer, 0, BUFFER_SIZE)) != -1)
            {
                out.write(buffer, 0, size);
            }
            in.close();
        } else
        {
            File files[] = file.listFiles();
            if (files.length >= 0)
                for (File listFile : files)
                {
                    zipImpl(listFile, out);
                }
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值