简体   繁体   中英

Java - Unzipping file returns FileNotFoundException

I'm trying to unzip a file using the method I had found online.

    public static void unzipFile(String zipFile, String outputFolder) throws IOException {
        File destDir = new File(outputFolder);
        if (!destDir.exists()) {
            destDir.mkdir();
        }
        ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry entry = zipIn.getNextEntry();
        while (entry != null) {
            String filePath = outputFolder + File.separator + entry.getName();
            if (!entry.isDirectory()) {
                extractFile(zipIn, filePath);
            } else {
                File dir = new File(filePath);
                dir.mkdir();
            }
            zipIn.closeEntry();
            entry = zipIn.getNextEntry();
        }
        zipIn.close();
    }

    public static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
        byte[] bytesIn = new byte[4096];
        int read = 0;
        while ((read = zipIn.read(bytesIn)) != -1) {
            bos.write(bytesIn, 0, read);
        }
        bos.close();
    }

However, I keep on getting FileNotFoundException BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));

Error message: java.io.FileNotFoundException: /Users/michael/NetBeansProjects/test/build/web/TEST_ZIP/my-html/css/bootstrap-theme.css (Not a directory)

I tried to alter the error line with:

File file = new File(filePath);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));

But didn't work either. Same error message is presented in console.

My ZIP file structure:

my-html
|
|- css
|   |
|   |- bootstrap-theme.css
|   |- ..
|   |- ..
|
|-index.html
destDir.mkdir();

Change this to:

destDir.mkdirs();

You are only creating one level of directory.

Make sure the output folder has no extension in its name like "/test.zip". Name it something like "output" or "myFolder"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM