Java URL Download downloadZip(URL file, File dump)

Here you can find the source of downloadZip(URL file, File dump)

Description

Downloads a Zip Archive and extracts it to specified folder.

License

Open Source License

Parameter

Parameter Description
file The URL to the zipped file.
dump The file to download and extract everything to.

Declaration

public static void downloadZip(URL file, File dump) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.*;
import java.net.*;
import java.util.zip.*;

public class Main {
    private static byte[] buffer = new byte[1024];

    /**//from  www. ja  v a 2 s.  c o  m
     * Downloads a Zip Archive and extracts it to specified folder.
     * 
     * @param file The URL to the zipped file.
     * @param dump The file to download and extract everything to.
     */
    public static void downloadZip(URL file, File dump) throws IOException {
        ZipInputStream in = new ZipInputStream(file.openStream());
        ZipEntry en = in.getNextEntry();
        while (en != null) {
            recursiveUnpack(in, en, dump);
            en = in.getNextEntry();
        }
        in.close();
    }

    private static void recursiveUnpack(ZipInputStream in, ZipEntry en, File dump) throws IOException {
        System.out.println(en.getName());
        String name = en.getName().replace("\\", "/");
        if (en.isDirectory()) {
            if (!name.endsWith("/"))
                name += "/";
            File f = new File(dump, en.getName());
            if (!f.exists())
                f.mkdirs();
        } else {
            File f = new File(dump, name);
            createDirFor(dump, name);
            FileOutputStream out = new FileOutputStream(f);
            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
            out.close();
        }
    }

    private static void createDirFor(File dump, String s) {
        try {
            String[] d = s.split("/");
            String x = "";
            for (int i = 0; i < d.length - 1; i++) {
                x += d[i] + "/";
            }
            File f = new File(dump, x);
            if (!f.exists()) {
                System.out.println("Creating directory: " + x);
                f.mkdirs();
            }
        } catch (Exception e) {

        }
    }
}

Related

  1. downloadURL(URL url, String localPath)
  2. downloadUrlToFile(String surl, File file, String method)
  3. downloadUrlToFile(URL url, File file)
  4. downloadUrlToFile(URL url, File result)
  5. downloadWebpage(String url)
  6. downlod(String url, File dest)
  7. downNetImg(String filePath, String remotePath, String htmlUrl, String fileName)
  8. downPicture(String filePath, String imageUrl, String fileName)
  9. fetchUrl(String _url, String charset)