在下载文件之前检查文件是否存在

Man*_*mad 3 android file android-download-manager

我正在使用下载管理器下载文件。下载文件的代码如下。

   private String DownloadData(Uri uri, View v, String textview) {

    long downloadReference;

    // Create request for android download manager
    dm = (DownloadManager)getContext().getSystemService(DOWNLOAD_SERVICE);
    DownloadManager.Request request = new DownloadManager.Request(uri);

    //Setting title of request
    request.setTitle(textview);

    //Setting description of request
    request.setDescription("Android Data download using DownloadManager.");

    //Set the local destination for the downloaded file to a path within the application's external files directory
    request.setDestinationInExternalFilesDir(getContext(), DIRECTORY_DOWNLOADS, File.separator + "Dr_Israr_Ahmad" + File.separator + textview+".mp3");

    //Enqueue download and save into referenceId
    downloadReference = dm.enqueue(request);

    return null
}
Run Code Online (Sandbox Code Playgroud)

上面的代码工作正常。我现在需要做的是,如果文件已经下载,而不是我想让我的应用程序播放它。使用的代码是

   String path = String.valueOf(getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS+ File.separator+"Dr_Israr_Ahmad" + File.separator +filename+".mp3"));

                File file = new File(path);

                if(file.exists()){
                    Toast.makeText(getContext(),path+ "/n exists", Toast.LENGTH_SHORT).show();
                } else if (!file.exists()) {
                    Toast.makeText(getContext(), "Downloading", Toast.LENGTH_SHORT).show();
                   Uri uri = Uri.parse("http://www.digitalsguide.com/mobile-apps/dr-israr-ahmad/audios/"+filename+".mp3");
                   String filepath = DownloadData(uri,view,filename);
                }
Run Code Online (Sandbox Code Playgroud)

但问题是即使文件不存在,条件也为真。我的路径有问题吗?请帮助我,

jep*_*bio 7

exists前一段时间我发现了一些奇怪的行为并将其更改为isFile

File file = new File(path);
if (file.isFile()) {
    Toast.makeText(getContext(), path + "/n exists", Toast.LENGTH_SHORT).show();
} else {
    Toast.makeText(getContext(), "Downloading", Toast.LENGTH_SHORT).show();
    // ...
}
Run Code Online (Sandbox Code Playgroud)

我认为每次new File()执行时,手机都会以某种方式创建一个目录。检查这个。