how to check if file is available in internal storage - android

I am trying to download a file from the internet and it succeeded but now
I want to check if the file exists in the internal storage.
else if (arg0.getId() == R.id.btn_download)
{
Toast.makeText(this, "download button clicked", Toast.LENGTH_SHORT).show();
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(names[b]));
request.setDescription("Downloading..");
request.setTitle("Futsing Magazine Issue " + (this.mPictureManager.getCurrentIndex() +1) );
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Futsing Magazine Issue " + (this.mPictureManager.getCurrentIndex()
+1) +".pdf");
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
The items retrieved are downloaded to /mnt/sdcard/Download.
How do I check if the file exists or not using code?

Let's say following is your file's path
String path=context.getFilesDir().getAbsolutePath()+"/filename";
File file = new File ( path );
if ( file.exists() )
{
// Toast File is exists
}
else
{
// Toast File is not exists
}

File applictionFile = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS)+ "/"+<file-name>);
if(applictionFile != null && applictionFile.exists()){
}
if file is getting downloads in to default donwload directory

Related

Not able to check whether file exists

I'm trying to download a file and if it exists to delete it and download again. The download works. But the function checkFile never finds the file and I don't know why.
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()
}
}
Thanks in advance.
You create the file in the public external storage directory with:
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS,
"$folderName/$fileName"
)
but you try to read it, from a relative (from the application's current directory) path:
val file = File(Environment.DIRECTORY_DOWNLOADS, "$folderName/$fileName")
You need to use the downloads directory, relative to the public external storage directory:
val file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "$folderName/$fileName")

Check If File Exists Before downloading the file

I am using download manager to download the file. The code for downloading the file is as follow.
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
}
The above code works fine. What i need to do now is if the file is already downloaded than i want my app to play it. The code which is used is
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);
}
but the problem is the condition is true even if the file doesn't exist. Is there a problem in my path ? kindly help me out,
I detected some strange behavior with exists time ago and changed it to 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();
// ...
}
I think the mobile, somehow, created a directory every time new File() was executed.
Check this.
Because getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) returns /storage/emulated/0/Android/data/<PACKAGE_ID>/files/Download. It's not the folder where DownloadManager downloads files when we set Environment.DIRECTORY_DOWNLOADS.
Try to put your path like the example shown below:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+ "/" +filename);
Here filename is example.pdf
you can then check if file exists or not
.getExternalFilesDir(yourFilePath) creates a directory in your code. so use it like this.
String path = String.valueOf(getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)+ File.separator+"Dr_Israr_Ahmad" + File.separator +filename+".mp3");

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);
}
}
change
if(applictionFile.exists()) {
Toast.makeText(getApplicationContext(), "File Already Exists",
Toast.LENGTH_LONG).show();
}
to
if(applictionFile.canRead()) {
Toast.makeText(getApplicationContext(), "File Already Exists",
Toast.LENGTH_LONG).show();
}
or
if(applictionFile.isFile()) {
Toast.makeText(getApplicationContext(), "File Already Exists",
Toast.LENGTH_LONG).show();
}
Try in simple way
File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) {
// do your code stuff
}
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");
on which testing device are you testing your app? is it above api-23 then you should have to set permission at the run time ! or else try this
File extStore = Environment.getExternalStorageDirectory();
File myFile = new File(extStore.getAbsolutePath() + "/mysongs.mp3");
if(myFile.exists()){
Toast.makeText(getApplicationContext(), "File Already Exists",
Toast.LENGTH_LONG).show();
}

How to save files with DownloadManager in private path?

I have downloaded some files with DownloadManager, I want to save them where that no one can access them, I mean they are private, just my application can access them and I want after uninstall my app they get deleted. but according to my search DownloadManager can save files just in SDCard that everyone can see my files.
can anyone tell me what to do?
You should probably use:
request.setDestinationInExternalFilesDir(context, DIRECTORY_DOWNLOADS, File.separator + folderName + File.separator + fileName);
Where request is your DownloadManager.Request
This folder (sdcard/Android/data/your.app.package) is accessible to the user, but not visible in galleries (not scanned by media scanner), it's only accessible using file manager. Also, this folder will be deleted when your app gets deleted.
You can use internal storage path to save data internally and it will get deleted when your app will get uninstalled
String dir = getFilesDir().getAbsolutePath();
For Set Your Path For Download File Use: Work For me (Android 11).
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/YOUR FOLDER/", "YOUR FILE.(mp3|mp4|pdf|...)");
request.setDestinationUri(Uri.fromFile(file));
Complete Code:
First Check Directory
private boolean CreateDirectory() {
boolean ret = false;
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getPath() + "/YOUR FOLDER/");
if (!dir.exists()) {
try {
dir.mkdirs();
ret = true;
} catch (Exception e) {
ret = false;
e.printStackTrace();
}
}
return ret;
}
Then:
String URL = " YOUR URL ";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(URL));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setTitle("YOUR TITLE");
request.setDescription("YOUR DESCRIPTION");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/YOUR FOLDER/", "YOUR FILE.(mp3|mp4|pdf|...)");
request.setDestinationUri(Uri.fromFile(file));
DownloadManager manager=(DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
Long downloadId= manager.enqueue(request);
ok,Finish

How to replace files in same location using Download manager in Android?

In my app I need to download some files(images,Pdf&txt). I am successful to save files through download manager in Downloads folder, But I want if file already exist in downloads folder and user again click on same file then it delete older one in download folder and replace with new file. Please let me know how it is possible?
My code:
database = new DMS_Database(Files_Folders_Activity.this);
if(!database.dididExist((doc_Id))) // if file does not exist then it will save file in the database and in downloads folder.
{
database.Save_Doc(doc_Id, name, url); //Database method
System.out.println("you are here: Save Files");
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setTitle(name);
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS + "/Downloads", name);
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
else
{
database.update_Doc(Doc_Id,name,url);
//But if file already exist then How to delete file and again save on same location. I don't want duplicate file. Right now it is creating two websites also not updating database.
System.out.println("you are here: update files");
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setTitle(name);
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS + "/Downloads", name);
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
database.close();
Please let mek now ow it is possible, thanks.

Categories

Resources