CoderMusgrove
CoderMusgrove

Reputation: 614

Java Download Zip from Webpage

I'm trying to download a zip file from a URL, and I have completed that. The problem is is that it keeps downloading the webpage itself, so I end up with some beautiful HTML, CSS, JS, and PHP. That's nowhere near a zip file.

Please correct me if I'm doing something wrong with my code:

private static String URL = "webpage/myzip.zip";
private static String OUTPUT_PATH = "path/to/extract/to";
private static File OUTPUT_DIRECTORY = new File(OUTPUT_PATH);

public static void create() throws Exception {
    if (!OUTPUT_DIRECTORY.exists()) OUTPUT_DIRECTORY.mkdirs();
    else return;

    System.out.println("Natives not found. Downloading.");

    BufferedInputStream in = null;
    FileOutputStream fout = null;

    try {
        in = new BufferedInputStream(new URL(URL).openStream());
        fout = new FileOutputStream(OUTPUT_PATH + File.separator + "myzip.zip");

        final byte[] data = new byte[4096];
        int count;

        while ((count = in.read(data, 0, 1024)) != -1) {
            fout.write(data, 0, count);
        }
    } finally {
        if (in != null) in.close();
        if (fout != null) fout.close();
    }

    OUTPUT_DIRECTORY = new File(OUTPUT_PATH);
    File zip = OUTPUT_DIRECTORY.listFiles()[0];

    ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zip));
    ZipEntry ze = zipIn.getNextEntry();

    byte[] buffer = new byte[4096];

    while (ze != null) {
        String fName = ze.getName();
        File newFile = new File(OUTPUT_DIRECTORY + File.separator + fName);

        new File(newFile.getParent()).mkdirs();

        FileOutputStream fos = new FileOutputStream(newFile);

        int len;
        while ((len = zipIn.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
        }

        fos.close();
        ze = zipIn.getNextEntry();
    }

    zipIn.closeEntry();
    zipIn.close();

//      zip.delete();

    System.out.println("Natives Downloaded.");
}

Upvotes: 1

Views: 582

Answers (1)

CoderMusgrove
CoderMusgrove

Reputation: 614

Answer provided by: Scary Wombat

I didn't copy the link correctly. I was using a drop box link, and I forgot that I needed to copy the download link from when you hit the download button.

Upvotes: 1

Related Questions