如何在android中获取下载的文件大小

时间:2016-08-22 08:43:08

标签: android file

我不知道如何获得总文件大小。这给了我-1总是

double totalSize = 0;
URL url = new URL(Constants.AUDIOURL+kid+".mp3");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
totalSize = (double)urlConnection.getContentLength();

3 个答案:

答案 0 :(得分:4)

请在下面找到代码段。它适用于您的情况。

try{
 URL uri = new URL(Constants.AUDIOURL+kid+".mp3");
 URLConnection urlconnection = uri.openConnection();
 urlconnection .connect();
 String fileLengthStr = urlconnection .getHeaderField("content-length");
 Log.d("File Size", fileLengthStr );     
}
catch(Exception exception){
 exception.printStackTrace();
}

答案 1 :(得分:0)

我用这段代码解决了

HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
urlConnection.setRequestProperty("Accept-Encoding", "identity");

答案 2 :(得分:0)

尝试使用上述URLConnection.getContentLength。如果服务器没有指定长度,那么你无法知道。

  final URLConnection connection = url.openConnection();
    final int length = connection.getContentLength();