Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java: Общие вопросы > Работа с zip архивами (для FAQ)


Автор: kudinov 30.3.2006, 11:33
Код

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * класс Archivator создан 27.02.2006 в 11:56:27
 * 
 * @author kudinov
 */
public class Archivator {

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        if (args.length < 3) {
            throw new IllegalArgumentException("usage Archivator arch dir");
        }
        if (args[0].equalsIgnoreCase("-x"))
            Archivator.extract(new File(args[1]),new File(args[2]));
        else {
            List files = new ArrayList();
            for (int i = 2; i < args.length; i++) {
                files.add(new File(args[i]));
            }
            Archivator.archive(new File(args[1]),(File[]) files.toArray(new File[0]));
        }
    }

    /**
     * удалить файл
     * 
     * @param f файл
     */
    public static void deleteFile(final File f) {
        new Thread() {
            public void run() {
                int counter = 0;
                while (f.exists()) {
                    f.delete();
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                    }
                    if (counter > 10) {
                        System.gc();
                        counter = 0;
                    }
                    if (counter > 20) {
                        break;
                    }
                }
                interrupt();
            }
        }.start();
    }

    /**
     * разархивировать архив в директорию
     * 
     * @param archive архив
     * @param toDir директория для разархивации
     * @throws IOException
     */
    public static void extract(File archive, File toDir) throws IOException {
        extract(archive,toDir,false);
    }

    /**
     * разархивировать архив в директорию
     * 
     * @param archive архив
     * @param toDir директория для разархивации
     * @param delArchive удалить архив
     * @throws IOException
     */
    public static void extract(File archive, File toDir, boolean delArchive) throws IOException {
        Enumeration<JarEntry> entries;
        JarFile jarFile = new JarFile(archive);
        entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry tmpEntry = entries.nextElement();
            File tmpfile = new File(tmpEntry.getName());
            if (tmpEntry.isDirectory()) {
                new File(toDir.getPath() + File.separator + tmpfile).mkdirs();
            } else {
                BufferedInputStream in = new BufferedInputStream(jarFile.getInputStream(tmpEntry));
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(toDir.getPath()
                            + File.separator + tmpfile));
                int i = -1;
                while ((i = in.read()) != -1) {
                    out.write(i);
                }
                out.flush();
                out.close();
                in.close();
            }
        }
        if (delArchive) {
            deleteFile(archive);
        }
    }

    /**
     * архивировать файлы
     * 
     * @param archive архив
     * @param fromDir откуда 
     * @param filter  фильтр
     * @throws IOException
     */
    public static void archive(File archive, File fromDir, FileFilter filter) throws IOException {
        archive(archive,fromDir.listFiles(filter));
    }

    /**
     * разархивировать архив в директорию
     * 
     * @param archive архив
     * @param files файлы
     * @throws IOException
     */
    public static void archive(File archive, File[] files) throws IOException {
        ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(archive)));
        try {
            for (File file : files) {
                FileInputStream fis = new FileInputStream(file);
                try {
                    zos.putNextEntry(new ZipEntry(file.getName()));
                    int read = -1;
                    byte[] buffer = new byte[8 * 1024];
                    while ((read = fis.read(buffer)) != -1) {
                        zos.write(buffer,0,read);
                    }
                    zos.closeEntry();
                } finally {
                    fis.close();
                }

            }
        } finally {
            zos.flush();
            zos.close();
        }
    }

}


Автор: LSD 30.3.2006, 11:58
А можешь добавить буковок? smile
Пояснения какие классы используются для работы с архивами, и как они между собой связанны. Такое небольшое описание.

Автор: ALKS 30.3.2006, 14:36
угу. мне, например, интересно почему такой размер буфера и что это дает.

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)