Search code examples
javaunzipepub

Can't Unzip EPub File


IMO, I thought that epub is a kind of zip . Thus, I've tried to unzip in a way.

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();
    } 
  }
}

I got that following error ..

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

though I've created a folder in that way .. and

my way of unzipping epub is right way ? .. Correct Me


Solution

  • I've got the answer.. I haven't checked that the object that have to be extracted is folder or not .

    I've corrected in this way .

    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());
                }
            }
        }
    

    Then, got it .