venura venura - 1 month ago 18
Android Question

Check whether the file is already exists Android not working

I want to check whether the file is already exists in Download folder in Android. I'm using Android download manager to download the file. In there

if
section is not working. If file is already there (Ex: File name - songname.mp3), when downloading the same file for the second time it's downloading the file as
songname1.mp3
. I have tried the code below. I want to show a message if the file is already there.

Please help me to fix this issue.

public void DownloadChecker() {
File applictionFile = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS)+ "/"+"mysongs.mp3");

if(applictionFile.exists()) {
Toast.makeText(getApplicationContext(), "File Already Exists",
Toast.LENGTH_LONG).show();
} else {
String servicestring = Context.DOWNLOAD_SERVICE;
DownloadManager downloadmanager;
downloadmanager = (DownloadManager) getSystemService(servicestring);
Uri uri = Uri.parse(DownloadUrl);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setDestinationInExternalFilesDir(MainActivity.this,
Environment.DIRECTORY_DOWNLOADS,"mysongs.mp3");

Long reference = downloadmanager.enqueue(request);
}
}

Answer

You should probably try changing:

File applictionFile =  new File(Environment.
        getExternalStoragePublicDirectory(Environment
                .DIRECTORY_DOWNLOADS)+ "/"+"mysongs.mp3");

to:

File applictionFile =  new File(Environment.
        getExternalStoragePublicDirectory(Environment
                .DIRECTORY_DOWNLOADS).getAbsolutePath() + "/" + "mysongs.mp3");