Delete files from a known folder - android

I'm trying to delete all files that are exists in a known path.
I've used the next function to do so -
public void deleteAllImages(){
Log.d(TAG, "ENTERD DELETED ALL IMAGES ");
String path = "/data/data/yourapp/app_data/imageDir/";
File directory = new File(path);
if (directory.isDirectory()){
Log.d(TAG, "ENTERED IF ");
for (File child : directory.listFiles()){
Log.d(TAG, "ENTERED FOR "+ child);
child.delete();
}
}
}
But it seem that it never getting into the if statement - guess it mean that it doesn't treat directory as one. So what am I doing wrong here?

Most likely the path is not correct. The isDirectory() will return false in the following cases:
The path points to file (obviously), and not to directory.
The path
is invalid (i.e. there is no such file/directory exists).
There is
not enough permissions granted to your application to determine
whether path points to directory.

Try this :
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
new File(dir, children[i]).delete();
}
}
Check this : Delete files from folder
Hope this helps.

try this...
String path = "/data/data/yourapp/app_data/imageDir/";
File file = new File(path);
if(file.isDirectory()) {
File[] files = file.listFiles();
if(files != null && files.length > 0) {
for (File file2 : files) {
file2.delete();
}
}
}

Related

How to open a directory which contains subdirectory in android?

can I open android directory mounted on sdcard should contain sub directories.
for example in ashish directory i had talasu and ash subdirectories.
The code which I had return :-
String root = Environment.getExternalStorageDirectory().toString();
File file = new File(root + "/ashish");
yes you can access those directories, heres a little code to help you out
File[] c = f.listFiles();//where f is your root directory(ashish)
if (c != null) {
for (int i = 0; i < c.length; i++) {
if (c[i].isDirectory()) {
//do whatever you want to do with subdirectories
}

Android: How to list all the files in a directory in to an array?

I have a variable "directorypath". It has the path to a directory in sd card.
Ex: "sdcard/images/scenes"
Now, I want to list all the files in the "directorypath" and want an Array to store all the file names in it.
Ex: Array[0]= Filename1, Array[1]= Filename2 Etc...
I tried something like Array[] myArray = directorypath.listfile(); but didn't work..!
Can anyone give me the code or at least help me? Much appreciated.
I think the problem you are facing is related to the external storage directory file path. Don't use whole path as variable if you can access with environment.
String path = Environment.getExternalStorageDirectory().toString()+"/images/scenes";
Also, you can use the API listfiles() with file object and it will work. For eg ::
File f = new File(path);
File file[] = f.listFiles();
Try the following code which may help you
List<File> getListFiles(File parentDir) {
ArrayList<File> inFiles = new ArrayList<File>();
File[] files = parentDir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
inFiles.addAll(getListFiles(file));
} else {
inFiles.add(file);
}
}
return inFiles;
}
This will return you list of files under the directory you specified.
From the File object in list.. you will get all information about files you required.
Try the following code:
File externalStorageDirectory = Environment.getExternalStorageDirectory();
File folder = new File(externalStorageDirectory.getAbsolutePath() + "/FilePath");
File file[] = folder.listFiles();
if (file.length != 0) {
for (int i = 0; i < file.length; i++) {
//here populate your list
}
} else {
//no file available
}
According to your error message "Cannot resolve listFiles()", you are trying to call a method on a String object, when you actually want to be calling that on a File object.
Create a new File object,
String parentDirectory = "path/to/files";
File dirFileObj = new File(parentDirectory);
File[] files = dirFileObj.listFiles();
I was indeed calling a function for improper data type. i.e., listfiles() won't work on String type variable..!!
SO, I created a File type variable and a File[] array to pass the list of files..!
This solved the issue.
its very simple Just two lines of code
File mListofFiles = new File(Environment.getExternalStorageDirectory.getAbsolutePath()+"/",childpath:Foldername);
File f = new File(mListofFiles.toString());
File file[] = f.listFiles();

File not deleting successfully in android

I have several image files in my sdcard inside the folder req_images. I want to delete all the image files in this folder. So I wrote the following code. The arraylist f stores the list of all image files in it in the form /mnt/sdcard/req_images/Image-1.jpg. When I try to delete all the files one by one using the for loop, the files are not deleting from my sd card. The boolean result which I get as output was false while I try to delete all the files. The file is still there in the sd card and I have checked it. What is the possible error in it.
ArrayList<String> f = new ArrayList<String>(); // list of available files in path
File[] listFile;
public void getSdcardImages()
{
File file= new File(android.os.Environment.getExternalStorageDirectory(),"req_images");
if (file.isDirectory())
{
listFile = file.listFiles();
for (int i = 0; i < listFile.length; i++)
{
f.add(listFile[i].getAbsolutePath());
}
}
}
for(int h=0;h<f.size();h++)
{
File fil=new File(f.get(h));
Boolean bool= fil.delete();
Log.d("File deletion status"+h,bool.toString());
}
Instead of doing it this way try a different approach
File dir = new File(Environment.getExternalStorageDirectory() + "/req_images");
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
new File(dir, children[i]).delete();
}
}

Android How do I check the number of files in a directory

I am creating a directory in internal memory of device for storing files for application use.I am using:
File dir = context.getDir(userfavorites, Context.MODE_PRIVATE);
The above code will create a new directory if it does not exists or returns me the existing file object if directory has already been created.What I want to check is the number and name of files this directory contains.How do I use this file object to accomplish this task.
NOTE:I don't want to use external memory of device.And I can't avoid creating directory as well because the files in directory has to be separated from other files that are not in directory.
UPDATED CODE:
private static boolean IsFoldercontainsFiles(Context context) {
// TODO Auto-generated method stub
File dir = context.getDir(USER_FAV, Context.MODE_PRIVATE);
if (dir.exists()) {
if (dir.listFiles() == null){
return false;} //it never execute this line even though its null
else{
File childfile[] = dir.listFiles();
Log.i("file no is ", Integer.toString(childfile.length));
if (childfile.length == 0) {
return false;
} else {
return true;
}
}
} else {
return false;
}
}
Thanks in advance
Check the listFiles method of File that will give you the list of children.
File file=new File("/mnt/sdcard/yourfolder");
File[] list = file.listFiles();
int count = 0;
for (File f: list){
String name = f.getName();
if (name.endsWith(".jpg") || name.endsWith(".mp3") || name.endsWith(".some media extention"))
count++;
System.out.println("170 " + count);
}
try this
File childfile[] = dir .listFiles();
for (File file2 : childfile) {
Log.v("file name is ", file2.getName());
}
here listFiles() return all the childfiles for the "dir" and iterating this will help you to get the names of the childfiles
Simple:
File dir = new File(path); // "/mnt/sdcard/yourfolder"
long totalNumFiles = dir.listFiles().length;
Try this sample of code for getting number of files in a directory
private int getNumberOfFiles() throws FileNotFoundException {
File outFile = new File(outFolder);
if (!outFile.exists())throw new FileNotFoundException();
int numberofFiles = outFile.listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
return (file.getPath().startsWith("frame_")&&(file.getPath().endsWith(".jpg")||file.getPath().endsWith(".jpeg")));
}
}).length;
return numberofFiles;
}
The listFiles method of the File class returns an array of File objects, one for each file or directory in the directory.
One can use recursion to find all files within a directory and its subdirectories.
fun File.getFileCountRecursively(): Int {
var fileCount = 0
if (exists() && isDirectory) {
listFiles()?.forEach { child ->
fileCount += if (child.isDirectory) child.getFileCountRecursively() else 1
}
}
return fileCount
}

How to get count of images stored in SD card

I need to calculate the number of images stored in SD card and so i would like to name the images unique like Sample0,Sample1,Sample2,Sample3,etc.
Is it Possible?
It gives the number of images present in the images folder of your SD card:
File dir = new File(Environment.getExternalStorageDirectory()
+ "/images");
File[] files = dir.listFiles();
int numberOfImages=files.length;
I now it's been a long time, but, the method above would give you the number of any kind of files and directories within images folder, not only the images number, and doesn't look for images in subfolders inside the images directory.
Let's say we have this structure:
Images/
- img1.jpg
- img2.jpg
- data.dat
- whatever.pdf
- Folder/
- img3.png
The method above will give you 5 and you should obtain 3 isn't it?
I've been working on something similar and I'm pretty sure there is a more efficient way, but with this method I get the number of all images within the SDCard, or any given directory and its subfolders...
Here we go:
public int countImgs(File file, int number) {
File[] dirs = file.listFiles();
String name = "";
if (dirs != null) { // Sanity check
for (File dir : dirs) {
if (dir.isFile()) { // Check file or directory
name = dir.getName().toLowerCase();
// Add or delete extensions as needed
if (name.endsWith(".png") || name.endsWith(".jpg")
|| name.endsWith(".jpeg")) {
number++;
}
} else number = countImgs(dir, number);
}
}
return number;
}
Where the param file is the root directory and the number would be 0 at start. So to use it:
int imgNumber = countImgs(Environment.getExternalStorageDirectory(), 0);
it will be an error when files = null when get the count of images stored in SD card
File dir = new File(Environment.getExternalStorageDirectory() + "/images");
File[] files = dir.listFiles();
String strnumberOfImages=files.length;
int intnumberOfImages= 0;
try{
intnumberOfImages = Integer.parseInt( strnumberOfImages);
}catch ( Exception e ){
intnumberOfImages = 0;
}
if just check empty or not
File dir = new File(Environment.getExternalStorageDirectory()+ "/images");
File[] files = dir.listFiles();
if(files != null){
// there are picz
}else{
// sd card empty
}

Categories

Resources