⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 filezip.java

📁 一个java实现的zip格式压缩
💻 JAVA
字号:
package zip;

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.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FileZip {
    static final char SEPARATOR = File.separatorChar;
    private int preffixLen = 0;

    public void compress(OutputStream out, File file) throws IOException {
        preffixLen = file.getParentFile().getAbsolutePath().length() + 1;
        ZipOutputStream zos = new ZipOutputStream(out);
        addFile(zos, file);
        zos.close();
    }

    private void addFile(ZipOutputStream zos, File file) throws IOException {
        String entryName = entryName(file);
        if (entryName.equals("") || entryName.equals("."))
            return;

        System.out.println("adding   " + entryName);
        ZipEntry entry = new ZipEntry(entryName);
        entry.setTime(file.lastModified());
        boolean isDirectory = file.isDirectory();
        if (isDirectory) {
            entry.setMethod(0);
            entry.setSize(0L);
            entry.setCrc(0L);
        } else
            entry.setSize(file.length());

        zos.putNextEntry(entry);
        if (isDirectory) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++)
                addFile(zos, files[i]);
        } else {
            byte buf[] = new byte[1024];
            BufferedInputStream bis = new BufferedInputStream(
                    new FileInputStream(file));
            int bytes;
            while ((bytes = bis.read(buf, 0, buf.length)) != -1)
                zos.write(buf, 0, bytes);
            bis.close();
        }
        zos.closeEntry();
    }

    private String entryName(File file) {
        String entryName = file.getPath();
        if (file.isDirectory())
            entryName = entryName.endsWith(File.separator) ? entryName
                    : entryName + File.separator;
        entryName = entryName.replace(File.separatorChar, '/').substring(
                preffixLen);
        return entryName;
    }

    public static void main(String args[]) {
        try {
            FileOutputStream fos = new FileOutputStream("test.zip"); //压缩到test.zip文件   
            FileZip zip = new FileZip();
            zip.compress(new BufferedOutputStream(fos), new File(
                    "c:\\downloads\\ggg")); //压缩目录c:\\downloads\\ggg   
            fos.close();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -