SoFunction
Updated on 2025-03-11

How to traverse all files in a specific directory

The first case shares that Android traverses all files in a specific directory, contains subdirectories, and deletes the latest created ones.

 private boolean deleteLastFromFloder(String path) {
    boolean success = false;
    try {
      ArrayList<File> images = new ArrayList<File>();
      getFiles(images, path);
      File latestSavedImage = (0);
      if (()) {
        for (int i = 1; i < (); i++) {
          File nextFile = (i);
          if (() > ()) {
            latestSavedImage = nextFile;
          }
        }

        ("brady", "images = " + ());
        success = ();
      }
    } catch (Exception e) {
      ();
    }
    return success;
  }

  private void getFiles(ArrayList<File> fileList, String path) {
    File[] allFiles = new File(path).listFiles();
    for (int i = 0; i < ; i++) {
      File file = allFiles[i];
      if (()) {
        (file);
      } else if (!().contains(".thumnail")) {
        getFiles(fileList, ());
      }
    }
  }

The second case introduces the folder traversal Android code for your reference. The specific content is as follows

package ;
 
import ;
import ;
import ;
/**
  * Folder traversal
  * @author once
  *
  */
public class DirTraversal {
   
  //no recursion
  public static LinkedList&lt;File&gt; listLinkedFiles(String strPath) {
    LinkedList&lt;File&gt; list = new LinkedList&lt;File&gt;();
    File dir = new File(strPath);
    File file = ();
    for (int i = 0; i &lt; ; i++) {
      if (())
        (file);
      else
        (());
    }
    File tmp;
    while (!()) {
      tmp = (File) ();
      if (()) {
        file = ();
        if (file == null)
          continue;
        for (int i = 0; i &lt; ; i++) {
          if (())
            (file);
          else
            (());
        }
      } else {
        (());
      }
    }
    return list;
  }
 
   
  //recursion
  public static ArrayList&lt;File&gt; listFiles(String strPath) {
    return refreshFileList(strPath);
  }
 
  public static ArrayList&lt;File&gt; refreshFileList(String strPath) {
    ArrayList&lt;File&gt; filelist = new ArrayList&lt;File&gt;();
    File dir = new File(strPath);
    File files = ();
 
    if (files == null)
      return null;
    for (int i = 0; i &lt; ; i++) {
      if (()) {
        refreshFileList(());
      } else {
        if(().toLowerCase().endsWith("zip"))
          (files);
      }
    }
    return filelist;
  }
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.