美文网首页
Android中File.exists()始终返回false/路

Android中File.exists()始终返回false/路

作者: Rimson | 来源:发表于2018-10-03 14:44 被阅读0次
    public static boolean fileIsExists(String strFile){
            try {
                File file=new File(strFile);
                if (!file.exists()){
                    return false;
                }
            }catch (Exception e){
                return false;
            }
            return true;
        }
    
    String downloadPath=Environment.getExternalStorageDirectory().getPath()+"/dailyarticle/sound/";
    
    if (fileIsExists(downloadPath+fileName)){
                //文件已存在
            }else {
                request.setDestinationInExternalPublicDir(downloadPath,fileName);
                DownloadManager downloadManager=(DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                downloadID = downloadManager.enqueue(request);
            }
    

    希望用这段代码,来实现判断文件是否存在,只有不存在时才下载,但运行时发现,即使文件存在,也会进入else语段。 (已经确定了读写权限没有问题)


    Screenshot_2018-10-03-14-39-01-660_com.android.fi.png

    仔细观察路径!!!发现问题所在了!!!路径中下面的语段重复了!!!

    /storage/emulated/0
    
    • File.exists()的参数需要绝对路径,也就是要用到Environment.getExternalStorageDirectory().getPath()方法
    • request.setDestinationInExternalPublicDir()的第一个参数,也就是文件路径,前面会自动添加上面的路径,例如传入参数"/dir/",实际上文件会保存至/storage/emulated/0/dir

    相关文章

      网友评论

          本文标题:Android中File.exists()始终返回false/路

          本文链接:https://www.haomeiwen.com/subject/czizoftx.html