Luke Batley
Luke Batley

Reputation: 2402

Android check if files exist in internal storage

Hi i have a string array of filenames and I'm wanting to loop through that array and check if any of the files exist in the internal files dir. If any of them don't exist i want to delete the ones that are there? does any one know how to do this?

Upvotes: 1

Views: 6919

Answers (4)

Sekhar Madhiyazhagan
Sekhar Madhiyazhagan

Reputation: 889

            File dir1 = getApplicationContext().getDir("your directory",
                Context.MODE_PRIVATE);

              // list the folder under the directory

        for (File fdir : dir1.listFiles()) {
            if (fdir.isDirectory()) {

                //list of file under the folder

                for (File wavfile : fdir
                        .listFiles()) {
                    String str = wavfile.getName().toString();

                    if (str.equals("your delete file"))) {

                        wavfile.delete();
                    }
                }
            }

Upvotes: 1

Nilesh Patel
Nilesh Patel

Reputation: 137

//Try this code

    // enter path of your dirctory
public void getDcimFolderImage(String path)
{
    File dir = new File(path);
    Log.e("path ", "is " + path);
    File file[] = dir.listFiles();

    try {
        if (file.length > 0)
        {
            for (int i = 0; i < file.length; i++) 
            {
                if (file[i].isFile()) 
                {

                    if (file.exists()
                    {
                       // enter your code whatever your want
                    }
                    else
                    {
                     // enter your code whatever your want
                    }

                }
                else 
                {
                        getDcimFolderImage(file[i].getAbsolutePath());
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }


}

Upvotes: 1

Hamid Shatu
Hamid Shatu

Reputation: 9700

String[] fileNames = {"a.txt", "b.txt", "c.txt"};

for(int i = 0; i < fileNames.length; i++) {
    File file = getBaseContext().getFileStreamPath(fileNames[i]);

    if (file.exists()) {

        file.delete();
    }
}

Upvotes: 1

NameSpace
NameSpace

Reputation: 10177

One Way:

    String[] paths = ...;

    for(String path: paths){
        File file = new File(path);

        if(file.exists()) 
            file.delete();    
    }

And another:

    File dir = new File("/pathToDir");
    File[] files = dir.listFiles();

    for(File file : files){
        //You Should not Exist!!!
        file.delete();
    }

Upvotes: 1

Related Questions