java zip file code example

Example 1: zip file java

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipCompress {
    public static void compress(String dirPath) {
        final Path sourceDir = Paths.get(dirPath);
        String zipFileName = dirPath.concat(".zip");
        try {
            final ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(zipFileName));
            Files.walkFileTree(sourceDir, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) {
                    try {
                        Path targetFile = sourceDir.relativize(file);
                        outputStream.putNextEntry(new ZipEntry(targetFile.toString()));
                        byte[] bytes = Files.readAllBytes(file);
                        outputStream.write(bytes, 0, bytes.length);
                        outputStream.closeEntry();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Example 2: Java create zip file

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class zip {

    public static void main(String[] args) {
    	zipFolder(mapFolder("Test"));
    	
        System.out.println("Done");
    }
    
	public static List<String> mapFolder(String path, boolean includeEmptyFolders) {
    	List<String> map = new ArrayList<String>();
    	List<String> unmappedDirs = new ArrayList<String>();
    	File[] items = new File(path).listFiles();

    	if (!path.substring(path.length() - 1).equals("/")) {
    		path += "/";
    	}
    		
    	if (items != null) {
	    	for (File item : items) {
	    		if (item.isFile()) {
	    				map.add(path+item.getName());
	    		} else {
	    			unmappedDirs.add(path+item.getName());
	    		}
	    	}
	    	
	    	if (!unmappedDirs.isEmpty()) {
	    		for (String folder : unmappedDirs) {
	    			List<String> temp = mapFolder(folder, includeEmptyFolders);
	    			if (!temp.isEmpty()) {
	    				for (String item : temp)
	    					map.add(item);
    				} else if (includeEmptyFolders == true) {
    					map.add(folder+"/");
    				}
	    		}
	    	}
    	}
    	return map;
    }
    
    public static void zipFolder(String zipPath, List<String> items) {
    	try {
            FileOutputStream f = new FileOutputStream(zipPath);
            ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(f));
            
            for (String item : items) {
            	String contents = String.join("\n", Files.readAllLines(Paths.get(item)));
            	zip.putNextEntry(new ZipEntry(item));
            	
            	byte[] data = contents.getBytes();
            	zip.write(data, 0, data.length);
            	zip.closeEntry();
            }
		    	
            zip.close();
            f.close();
        } catch(Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

Example 3: reading zip file in java

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

/**
 * Java program to iterate and read file entries from Zip archive.
 * This program demonstrate two ways to retrieve files from Zip using ZipFile and by using ZipInputStream class.
 * @author Javin
 */

public class ZipFileReader {

    // This Zip file contains 11 PNG images
    private static final String FILE_NAME = "C:\\temp\\pics.zip";
    private static final String OUTPUT_DIR = "C:\\temp\\Images\\";
    private static final int BUFFER_SIZE = 8192;

    public static void main(String args[]) throws IOException {

        // Prefer ZipFile over ZipInputStream
        readUsingZipFile();
    //  readUsingZipInputStream();

    }

    /*
     * Example of reading Zip archive using ZipFile class
     */

    private static void readUsingZipFile() throws IOException {
        final ZipFile file = new ZipFile(FILE_NAME);
        System.out.println("Iterating over zip file : " + FILE_NAME);

        try {
            final Enumeration<? extends ZipEntry> entries = file.entries();
            while (entries.hasMoreElements()) {
                final ZipEntry entry = entries.nextElement();
                System.out.printf("File: %s Size %d  Modified on %TD %n", entry.getName(), entry.getSize(), new Date(entry.getTime()));
                extractEntry(entry, file.getInputStream(entry));
            }
            System.out.printf("Zip file %s extracted successfully in %s", FILE_NAME, OUTPUT_DIR);
        } finally {
            file.close();
        }

    }

    /*
     * Example of reading Zip file using ZipInputStream in Java.
     */

    private static void readUsingZipInputStream() throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(FILE_NAME));
        final ZipInputStream is = new ZipInputStream(bis);

        try {
            ZipEntry entry;
            while ((entry = is.getNextEntry()) != null) {
                System.out.printf("File: %s Size %d  Modified on %TD %n", entry.getName(), entry.getSize(), new Date(entry.getTime()));
                extractEntry(entry, is);
            }
        } finally {
            is.close();
        }

    }

    /*
     * Utility method to read  data from InputStream
     */

    private static void extractEntry(final ZipEntry entry, InputStream is) throws IOException {
        String exractedFile = OUTPUT_DIR + entry.getName();
        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream(exractedFile);
            final byte[] buf = new byte[BUFFER_SIZE];
            int read = 0;
            int length;

            while ((length = is.read(buf, 0, buf.length)) >= 0) {
                fos.write(buf, 0, length);
            }

        } catch (IOException ioex) {
            fos.close();
        }

    }

}

Output:
Iterating over zip file : C:\temp\pics.zip
File: Image  (11).png Size 21294  Modified on 10/24/13
File: Image  (1).png Size 22296  Modified on 11/19/13
File: Image  (2).png Size 10458  Modified on 10/24/13
File: Image  (3).png Size 18425  Modified on 11/19/13
File: Image  (4).png Size 31888  Modified on 11/19/13
File: Image  (5).png Size 27454  Modified on 11/19/13
File: Image  (6).png Size 67608  Modified on 11/19/13
File: Image  (7).png Size 8659  Modified on 11/19/13
File: Image  (8).png Size 40015  Modified on 11/19/13
File: Image  (9).png Size 17062  Modified on 10/24/13
File: Image  (10).png Size 42467  Modified on 10/24/13
Zip file C:\temp\pics.zip extracted successfully in C:\temp\Images\

Tags:

Java Example