Не могу разархивировать файл EPub

ИМО, я думал, что epub — это своего рода zip . Таким образом, я попытался разархивировать способ.

public class Main {
    public static void main(String argv[ ])  {
        final int BUFFER = 2048;

    try {
        BufferedOutputStream dest = null;
        FileInputStream fis = new FileInputStream("/Users/yelinaung/Documents/unzip/epub/doyle.epub");
        ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            System.out.println("Extracting: " + entry);
            int count;
            byte data[] = new byte[BUFFER];
            // write the files to the disk
            FileOutputStream fos = new FileOutputStream("/Users/yelinaung/Documents/unzip/xml/");
            dest = new BufferedOutputStream(fos, BUFFER);
            while ((count = zis.read(data, 0, BUFFER))
                    != -1) {
                dest.write(data, 0, count);
            }
            dest.flush();
            dest.close();
        }
        zis.close();
    } catch ( IOException e) {
        e.printStackTrace();
    } 
  }
}

Я получил следующую ошибку..

java.io.FileNotFoundException: /Users/yelinaung/Documents/unzip/xml (No such file or directory)

хотя я создал папку таким образом .. и

мой способ разархивировать epub правильный путь? .. Исправь меня


person Ye Lin Aung    schedule 30.06.2010    source источник


Ответы (3)


У меня есть ответ. Я не проверял, является ли объект, который нужно извлечь, папкой или нет.

Я исправил таким образом.

public static void main(String[] args) throws IOException {
        ZipFile zipFile = new ZipFile("/Users/yelinaung/Desktop/unzip/epub/doyle.epub");
        String path = "/Users/yelinaung/Desktop/unzip/xml/";

        Enumeration files = zipFile.entries();

        while (files.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) files.nextElement();
            if (entry.isDirectory()) {
                File file = new File(path + entry.getName());
                file.mkdir();
                System.out.println("Create dir " + entry.getName());
            } else {
                File f = new File(path + entry.getName());
                FileOutputStream fos = new FileOutputStream(f);
                InputStream is = zipFile.getInputStream(entry);
                byte[] buffer = new byte[1024];
                int bytesRead = 0;
                while ((bytesRead = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, bytesRead);
                }
                fos.close();
                System.out.println("Create File " + entry.getName());
            }
        }
    }

Тогда, понял.

person Ye Lin Aung    schedule 02.07.2010

Вы создаете FileOutputStream с тем же именем для каждого файла внутри вашего файла epub.

FileNotFoundException выбрасывается, если файл существует и является каталогом. При первом прохождении цикла каталог создается, а в следующий раз возникает исключение.

Если вы хотите изменить каталог, в который распаковывается epub, вы должны сделать что-то вроде этого:

FileOutputStream fos = new FileOutputStream("/Users/yelinaung/Documents/unzip/xml/" + entry.getName())

Обновить
Создание папки перед извлечением каждого файла. Мне удалось открыть файл epub.

...
byte data[] = new byte[BUFFER];

String path = entry.getName();
if (path.lastIndexOf('/') != -1) {
    File d = new File(path.substring(0, path.lastIndexOf('/')));
    d.mkdirs();
}

// write the files to the disk
FileOutputStream fos = new FileOutputStream(path);
...

И чтобы изменить папку, в которую извлекаются файлы, просто измените строку, где определяется путь

String path = "newFolder/" + entry.getName();
person Ed.    schedule 01.07.2010
comment
эээ... я пробовал... и снова получил ту же ошибку... он может извлекать файлы... но не папки... META-INF извлекается как файл... на самом деле это подпапка файла .epub. - person Ye Lin Aung; 01.07.2010

Этот метод отлично сработал для меня,

public void doUnzip(String inputZip, String destinationDirectory)
        throws IOException {
    int BUFFER = 2048;
    List zipFiles = new ArrayList();
    File sourceZipFile = new File(inputZip);
    File unzipDestinationDirectory = new File(destinationDirectory);
    unzipDestinationDirectory.mkdir();

    ZipFile zipFile;
    // Open Zip file for reading
    zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);

    // Create an enumeration of the entries in the zip file
    Enumeration zipFileEntries = zipFile.entries();

    // Process each entry
    while (zipFileEntries.hasMoreElements()) {
        // grab a zip file entry
        ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();

        String currentEntry = entry.getName();

        File destFile = new File(unzipDestinationDirectory, currentEntry);

        if (currentEntry.endsWith(".zip")) {
            zipFiles.add(destFile.getAbsolutePath());
        }

        // grab file's parent directory structure
        File destinationParent = destFile.getParentFile();

        // create the parent directory structure if needed
        destinationParent.mkdirs();

        try {
            // extract file if not a directory
            if (!entry.isDirectory()) {
                BufferedInputStream is =
                        new BufferedInputStream(zipFile.getInputStream(entry));
                int currentByte;
                // establish buffer for writing file
                byte data[] = new byte[BUFFER];

                // write the current file to disk
                FileOutputStream fos = new FileOutputStream(destFile);
                BufferedOutputStream dest =
                        new BufferedOutputStream(fos, BUFFER);

                // read and write until last byte is encountered
                while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, currentByte);
                }
                dest.flush();
                dest.close();
                is.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
    zipFile.close();

    for (Iterator iter = zipFiles.iterator(); iter.hasNext();) {
        String zipName = (String)iter.next();
        doUnzip(
            zipName,
            destinationDirectory +
                File.separatorChar +
                zipName.substring(0,zipName.lastIndexOf(".zip"))
        );
    }

}
person Andro Selva    schedule 02.07.2012