我正在构建一个 Android 应用程序,我需要从一个 33 MB 的 url 下载一个文件。
这里是下载任务:
try {
int MAX_BUFFER_SIZE = 4096;
URL mUrl = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) mUrl.openConnection();
connection.setRequestMethod("GET");
long length = connection.getContentLength(), downloaded = 0;
int read;
byte [] buffer = new byte[(((int)length) > MAX_BUFFER_SIZE) ? MAX_BUFFER_SIZE : (int)length];
String filename = getFilename(mUrl);
File file = new File (SDCARD_ROOT);
if (!file.exists() || !file.isDirectory()){
file.mkdir();
}
this.filename = filename;
file = new File (SDCARD_ROOT + this.filename);
FileOutputStream fos = new FileOutputStream (file);
//Start downloading
InputStream stream = connection.getInputStream();
while ((read=stream.read(buffer)) > -1){
fos.write(buffer, 0, read);
downloaded += read;
publishProgress((int) ((float) downloaded/length * 100));
}
fos.close();
return 1;
} catch (Exception e){
Log.e("REV-PARTS", "Revolver parts error in DownloadTask: " + e.getMessage());
return 2;
}
它适用于小文件 (1-15 MB),但对于大文件它会返回“流的意外结束”异常。
最佳答案
设置 block 大小似乎对我有用。
connection.setChunkedStreamingMode(1048576);
关于java - Android :"Unexpected end of stream"下载大文件异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7402500/