Java从网页下载Zip

时间:2014-07-14 02:24:28

标签: java url zip

我试图从zip下载URL文件,我已经完成了。{I}}问题是它不断下载网页本身,所以我最终得到了一些漂亮的HTML,CSS,JS和PHP。那个拉链文件附近没有。

如果我的代码出错,请纠正我:

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.");
}

1 个答案:

答案 0 :(得分:1)

答案提供者:Scary Wombat

我没有正确复制链接。我正在使用投递箱链接,我忘记了当你点击下载按钮时我需要复制下载链接。