Search code examples
javaandroidfiledirectoryassets

List all files and folders (also Subfolders) in Assets Directory in my App and check if an asset is a file or a folder


I want to check if the asset in Assets directory of my Android App is a File or a Directory.

I have already tried every solution available anywhere on internet including StackOverflow.

Most of the solutions use

File myFile = new File(path);

then check for myFile.isDirectory(); or myFile.isFile();

But it works only if I have my files and directories anywhere else other than under the Assets directory.

Any suggestions will be highly appreciated.


Solution

  • Here is a solution to my problem that I found out working 100% listing all directories and files even sub-directories and files in subdirectories. It also works for multiple levels.

    Note: In my case

    1. Filenames had a . in them. i.e. .htm .txt etc
    2. Directorynames did not have any . in them.

    Note: about -- path --

    1. to get all files and directories in Assets root folder

      String path = ""; // assets

    2. or to get files and directories in a subfolder use its name as path

      String path = "html"; // <<-- assets/html

      listAssetFiles2(path); // <<-- Call function where required
      //function to list files and directories
      public void listAssetFiles2 (String path){
      String [] list;
      
      try {
          list = getAssets().list(path);
          if(list.length > 0){
              for(String file : list){
                  System.out.println("File path = "+file);
      
                  if(file.indexOf(".") < 0) { // <<-- check if filename has a . then it is a file - hopefully directory names dont have . 
                      System.out.println("This is a folder = "+path+"/"+file);
                      if(path.equals("")) {
                          listAssetFiles2(file); // <<-- To get subdirectory files and directories list and check 
      
                      }else{
                          listAssetFiles2(path+"/"+file); // <<-- For Multiple level subdirectories
                      }
                  }else{
                      System.out.println("This is a file = "+path+"/"+file);
                  }
              }
      
          }else{
              System.out.println("Failed Path = "+path);
              System.out.println("Check path again.");
          }
      }catch(IOException e){
          e.printStackTrace();
      }
      

      }

    Thanks