如何将较大的文件从URL保存到本地

时间:2018-11-01 10:47:11

标签: java

我在下面的代码中尝试过此代码,该代码可以很好地处理小型文件。

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

任何人都可以帮助我。

2 个答案:

答案 0 :(得分:0)

您尝试下载的URL无效。网址不能包含空格。您需要对其进行URL编码:

https://dl.dropboxusercontent.com/1/view/79q8i6f9zqx7y2w/Paragliding%20in%20Himalayas.avi 

请参阅:how do I encode a complete http url String correctly?,以获取编码URL的方法。不幸的是,仅使用URLEncoder.encode()不会削减它,因为它会编码斜杠等。

答案 1 :(得分:-1)

您可以使用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()
}