[英]Not able to check whether file exists
我正在嘗試下載一個文件,如果它存在,請刪除它並再次下載。
下載有效。 但是 function checkFile
永遠找不到文件,我不知道為什么。
private fun startDownloading() {
checkFile()
val url = etUrl.text.toString()
val request = DownloadManager.Request(Uri.parse(url))
//allow type of networks to download file(s) by default, by default both are allowed
request.setAllowedNetworkTypes((DownloadManager.Request.NETWORK_MOBILE or DownloadManager.Request.NETWORK_WIFI))
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "$folderName/$fileName")
//get download service, and enqueue file
val manager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
manager.enqueue(request)
}
private fun checkFile(){
val file = File(Environment.DIRECTORY_DOWNLOADS, "$folderName/$fileName")
if(file.exists()){
Toast.makeText(this, "File exists", Toast.LENGTH_LONG).show()
file.delete()
}else{
Toast.makeText(this, file.toString() + " doesn't exist", Toast.LENGTH_LONG).show()
}
}
提前致謝。
您使用以下命令在公共外部存儲目錄中創建文件:
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS,
"$folderName/$fileName"
)
但是您嘗試從相對(從應用程序的當前目錄)路徑中讀取它:
val file = File(Environment.DIRECTORY_DOWNLOADS, "$folderName/$fileName")
您需要使用相對於公共外部存儲目錄的下載目錄:
val file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "$folderName/$fileName")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.