download File from URL and Unzip - Java File Path IO

Java examples for File Path IO:Zip File

Description

download File from URL and Unzip

Demo Code


import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class Main{

    public static void downloadFileInto(CharSequence stringURL,
            File directory) {//from  w  w w.  j ava2s  .  c  o  m
        try {
            URL url = new URL(stringURL.toString());
            unzipIntoDirectory(url.openStream(), directory);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void unzipIntoDirectory(File file, File directory) {
        try {
            unzipIntoDirectory(new FileInputStream(file), directory);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    public static void unzipIntoDirectory(InputStream inputStream,
            File directory) {
        if (directory.isFile())
            return;
        directory.mkdirs();

        try {
            inputStream = new BufferedInputStream(inputStream);
            inputStream = new ZipInputStream(inputStream);

            for (ZipEntry entry = null; (entry = ((ZipInputStream) inputStream)
                    .getNextEntry()) != null;) {
                StringBuilder pathBuilder = new StringBuilder(
                        directory.getPath()).append('/').append(
                        entry.getName());
                File file = new File(pathBuilder.toString());

                if (entry.isDirectory()) {
                    file.mkdirs();
                    continue;
                }

                StreamUtil.write(pathBuilder, inputStream, false);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            StreamUtil.closeQuietly(inputStream);
        }
    }
}

Related Tutorials