2013-09-26 32 views
1

我想使用此代碼從web服務下載大型(11MB)JSON文件之前檢索文件大小:的Java的HttpConnection下載

public static void downloadBigFile(final String serverUrl, 
     final String fileName) throws MalformedURLException, IOException { 
    System.out.println("Downloading " + serverUrl + " (" + fileName + ")"); 

    URL url = new URL(serverUrl); 
    URLConnection con = url.openConnection(); 
    con.setConnectTimeout(10000); 
    con.setReadTimeout(2 * 60 * 1000); 

    int totalFileSize = con.getContentLength(); 
    System.out.println("Total file size: " + totalFileSize); 

    InputStream inputStream = con.getInputStream(); 
    FileOutputStream outputStream = new FileOutputStream(fileName); 

    // Used only for knowing the amount of bytes downloaded. 
    int downloaded = 0; 

    final byte[] buffer = new byte[1024 * 8]; 
    int bytesRead; 

    bytesRead = inputStream.read(buffer); 

    while (bytesRead != -1) { 
     downloaded += bytesRead; 
     outputStream.write(buffer, 0, bytesRead); 
     bytesRead = inputStream.read(buffer); 

     System.out.println(String.format("%d/%d (%.2f%%)", downloaded, 
       totalFileSize, 
       (downloaded * 1.0/totalFileSize * 1.0) * 100)); 
    } 

    System.out 
      .println(fileName + " downloaded! (" + downloaded + " bytes)"); 

    inputStream.close(); 
    outputStream.close(); 
} 

但是調用con.getContentLength()阻止該線程幾分鐘,而它下載我認爲的整個文件。

問題是我需要一個快速的方法來在下載開始之前發現文件大小,以便我可以相應地通知用戶。

注意:已嘗試致電con.connect()con.getHeaderField("Content-Length")

回答

1

如果服務器沒有指定Content-Length標題,獲取內容長度的唯一方法是下載整個文件並查看其大小。