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

我在下面的代码中尝试了这个,它在小文件中运行良好。


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

谁能帮我。




幕布斯6054654
浏览 148回答 2
2回答

函数式编程

您尝试下载的 URL 无效。URL 不能包含空格。您需要对其进行 URL 编码:https://dl.dropboxusercontent.com/1/view/79q8i6f9zqx7y2w/Paragliding%20in%20Himalayas.avi看看:如何正确编码完整的 http url 字符串?,用于对 URL 进行编码的方法。不幸的是,只是使用URLEncoder.encode()不会削减它,因为它编码斜杠等。

holdtom

您可以使用 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()}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java