2014-07-14 23 views
1

我试图从URL下载zip文件,我已经完成了。问题在于它一直在下载网页本身,所以我最终得到了一些漂亮的HTML,CSS,JS和PHP。这是靠近一个zip文件。Java下载从网页的邮编

请纠正我,如果我做错了我的代码:提供

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

如果您在浏览器中输入网址,会发生什么情况? –

+0

'新的URL(URL).openStream()'? –

+0

感谢Help @ScaryWombat,我以为只要在链接中加入“zip”就可以让它变得很好。这是一个Dropbox链接,我忘记了我需要复制单击按钮时提供的链接。 – CoderMusgrove

回答

1

答:可怕的袋熊

我没有正确复制链接。我正在使用下拉框链接,并且我忘记了我需要从下载按钮时复制下载链接。