1

I saved some images in my storage's specific folder.I have fro example 1.png,2.png and etc. I know how i can get all files's name.This is source

  private void getAllElemetsFromStorage() {
    String root_sd = Environment.getExternalStorageDirectory().toString();
    File file = new File(root_sd + "/myfolder");
    for (File f : file.listFiles()) {
        if (f.isFile()) {
            String name = f.getName();
            Log.e("file names", name + "");
        }}
}

This code working correct but i have one problem.I have some json and in my json i have file's name.How i can get all files name witch is not in my json and is my directory and how i can delete all this files? My goal is to save only files,witch are in my jsons and i want to delete all unused files from my directory How i can solve my problem? thanks

BekaKK
  • 2,173
  • 6
  • 42
  • 80

1 Answers1

1

Inside your if statement, after you get the file name, loop through the json and check whether its in there or not. If not, delete it.

Your for loop that exists already will do this for every file in the directory, removing it if the name doesnt exist in the json.

Below is an example. Depending on your Json, you need to build a list or loop through another way.

private void getAllElemetsFromStorage() {
  String root_sd = Environment.getExternalStorageDirectory().toString();
  File file = new File(root_sd + "/myfolder");
  ArrayList<String> jsonFileNames = // Get list of file names from json

  for (File f : file.listFiles()) {
    if (f.isFile()) {
        String name = f.getName();      

        // If not found in json. Delete file
        if(!jsonFileNames.contains(name))
           f.delete();
    }
  }
}

Note: this code is untested so may be typos. But it should give you the idea.

IAmGroot
  • 13,760
  • 18
  • 84
  • 154
  • 1
    Thanks men .Maybe i solved myself if(!jsonFileNames.contains(name)) { Log.e("delete this file", name + ""); }.What do you think? Is this correct @Doomsknight – BekaKK Jun 13 '17 at 11:29
  • @Baggio Yep, much better. I couldnt remember for sure if there was a contains method on array list. Ive changed my answer to reflect – IAmGroot Jun 13 '17 at 11:30
  • I try to delete file but f.delete() not working correct.it's cleared all my directory ? @Doomsknight – BekaKK Jun 14 '17 at 06:59
  • @Baggio. Log which ones you are calling delete on. Maybe its called on each file? if so, check the contents of `jsonfilenames` and `name`. Make sure the extension exists/doesnt exist in both sources. As it may consider it "not found" if there is a mismatch. [removing extension](https://stackoverflow.com/a/8393894/940834) – IAmGroot Jun 14 '17 at 08:06