[英]How do I save a large file from a URL to the local
我已經嘗試了下面的代碼,該代碼可以很好地處理小型文件。
URL url = new URL(downloadLink);
ReadableByteChannel rbc = Channels.newChannel(url.openStream());
FileOutputStream fos = new FileOutputStream(newFile);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
如果文件是大文件,則出現類似以下錯誤:
java.io.IOException:Server returned HTTP response code: 400 for URL:https://dl.dropboxusercontent.com/1/view/79q8i6f9zqx7y2w/Paragliding in Himalayas.avi
誰能幫我。
您嘗試下載的URL無效。 網址不能包含空格。 您需要對其進行URL編碼:
https://dl.dropboxusercontent.com/1/view/79q8i6f9zqx7y2w/Paragliding%20in%20Himalayas.avi
看一下: 如何正確編碼完整的http url字符串? ,用於編碼URL的方法。 不幸的是,僅使用URLEncoder.encode()
不會削減它,因為它會編碼斜線等。
您可以使用DownloadManager將此任務移交給Os本身
private fun startDownload(url: String) {
val request = DownloadManager.Request(Uri.parse(url))
request.allowScanningByMediaScanner()
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, url.substring(url.lastIndexOf("/")))
val dm = activity!!.getSystemService(DOWNLOAD_SERVICE) as DownloadManager
dm.enqueue(request)
Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.