Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

public class Main {

    public static void compressDir(File file) throws IOException {
        FileOutputStream f = new FileOutputStream(file.getParent() + file.getName() + ".zip");
        CheckedOutputStream cs = new CheckedOutputStream(f, new Adler32());
        ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(cs));

        compressDir(file, out, file.getAbsolutePath());

        out.flush();
        out.close();
    }

    private static void compressDir(File srcFile, ZipOutputStream out, String destPath) throws IOException {
        if (srcFile.isDirectory()) {
            File subfile[] = srcFile.listFiles();
            for (int i = 0; i < subfile.length; i++) {
                compressDir(subfile[i], out, destPath);
            }
        } else {
            InputStream in = new FileInputStream(srcFile);
            String name = srcFile.getAbsolutePath().replace(destPath, "");
            if (name.startsWith("\\"))
                name = name.substring(1);
            ZipEntry entry = new ZipEntry(name);
            entry.setSize(srcFile.length());
            entry.setTime(srcFile.lastModified());
            out.putNextEntry(entry);
            int len = -1;
            byte buf[] = new byte[1024];
            while ((len = in.read(buf, 0, 1024)) != -1)
                out.write(buf, 0, len);

            out.closeEntry();
            in.close();
        }
    }
}