64

I have some folders with HTML files in the "assets" folder in my Android project. I need to show these HTML files from assets' sub-folders in a list. I already wrote some code about making this list.

lv1 = (ListView) findViewById(R.id.listView);
// Insert array in ListView

// In the next row I need to insert an array of strings of file names
// so please, tell me, how to get this array

lv1.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, filel));
lv1.setTextFilterEnabled(true);
// onclick items in ListView:
lv1.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> a, View v, int position, long id) {
        //Clicked item position
        String itemname = new Integer(position).toString();  
        Intent intent = new Intent();
        intent.setClass(DrugList.this, Web.class);
        Bundle b = new Bundle();
        //I don't know what it's doing here
        b.putString("defStrID", itemname); 
        intent.putExtras(b);
        //start Intent
        startActivity(intent);
    }
});
Jared Rummler
  • 37,824
  • 19
  • 133
  • 148
Max L
  • 1,453
  • 2
  • 17
  • 32

8 Answers8

114
private boolean listAssetFiles(String path) {

    String [] list;
    try {
        list = getAssets().list(path);
        if (list.length > 0) {
            // This is a folder
            for (String file : list) {
                if (!listAssetFiles(path + "/" + file))
                    return false;
                else {
                    // This is a file
                    // TODO: add file name to an array list
                }
            }
        } 
    } catch (IOException e) {
        return false;
    }

    return true; 
} 

Call the listAssetFiles with the root folder name of your asset folder.

    listAssetFiles("root_folder_name_in_assets");

If the root folder is the asset folder then call it with

    listAssetFiles("");    
Kammaar
  • 1,611
  • 1
  • 14
  • 12
27

try this it will work in your case

f = getAssets().list("");
for(String f1 : f){
    Log.v("names",f1);
}

The above snippet will show the contents of the asset root.

For example... if below is the asset structure..

assets
 |__Dir1
 |__Dir2
 |__File1

Snippet's output will be .... Dir1 Dir2 File1

If you need the contents of the Directory Dir1

Pass the name of Directory in the list function.

  f = getAssets().list("Dir1");
cafebabe1991
  • 4,928
  • 2
  • 34
  • 42
  • 1
    I edited this code, because Eclipse showing errors. `String[] f = null; try { f = getAssets().list(""); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } for(String f1:f){ Log.v("names",f1); } ` to this – Max L Apr 26 '13 at 11:30
  • 1
    And as result - emulator shows me 4 items list: drugs, images, sounds, webkit – Max L Apr 26 '13 at 11:33
  • 2
    Ya it shows that..but passing the name of youtlr directory inside asset can help you get rid of it pass inside the bracket your parent folder and all its content will be listed......like getAssets().list("drugs"); – cafebabe1991 Apr 26 '13 at 13:29
  • You need to repeat the same process for gwtting the files in every folder inside your assets folder...instead make an array of string having the folder names and keep passing them insidethe list function – cafebabe1991 Apr 26 '13 at 14:59
3

Hope This Help:

following code will copy all the folder and it's content and content of sub folder to sdcard location:

 private void getAssetAppFolder(String dir) throws Exception{

    {
        File f = new File(sdcardLocation + "/" + dir);
        if (!f.exists() || !f.isDirectory())
            f.mkdirs();
    }
     AssetManager am=getAssets();

     String [] aplist=am.list(dir);

     for(String strf:aplist){
        try{
             InputStream is=am.open(dir+"/"+strf);
             copyToDisk(dir,strf,is);
         }catch(Exception ex){


            getAssetAppFolder(dir+"/"+strf);
         }
     }



 }


 public void copyToDisk(String dir,String name,InputStream is) throws IOException{
     int size;
        byte[] buffer = new byte[2048];

        FileOutputStream fout = new FileOutputStream(sdcardLocation +"/"+dir+"/" +name);
        BufferedOutputStream bufferOut = new BufferedOutputStream(fout, buffer.length);

        while ((size = is.read(buffer, 0, buffer.length)) != -1) {
            bufferOut.write(buffer, 0, size);
        }
        bufferOut.flush();
        bufferOut.close();
        is.close();
        fout.close();
 }
Koushik
  • 345
  • 1
  • 7
1

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.

Note: In my case

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

    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);
                    listAssetFiles2(file); // <<-- To get subdirectory files and directories list and check 
                }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();
    }
    }//now completed
    

Thanks

Puneet
  • 615
  • 2
  • 7
  • 17
MindRoasterMir
  • 324
  • 1
  • 2
  • 18
1

i think that this is best that check file is dir or not, altarnative try,catch!

 public static  List<String> listAssetFiles(Context c,String rootPath) {
    List<String> files =new ArrayList<>();
    try {
        String [] Paths = c.getAssets().list(rootPath);
        if (Paths.length > 0) {
            // This is a folder
            for (String file : Paths) {
                String path = rootPath + "/" + file;
                if (new File(path).isDirectory())
                    files.addAll(listAssetFiles(c,path));
                else files.add(path);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
   return files;
}
abbasalim
  • 3,118
  • 2
  • 23
  • 45
0

Based on the @Kammaar answer. This kotlin code scans the file tree for the leafs:

private fun listAssetFiles(path: String, context: Context): List<String> {
    val result = ArrayList<String>()
    context.assets.list(path).forEach { file ->
        val innerFiles = listAssetFiles("$path/$file", context)
        if (!innerFiles.isEmpty()) {
            result.addAll(innerFiles)
        } else {
            // it can be an empty folder or file you don't like, you can check it here
            result.add("$path/$file")
        }
    }
    return result
}
vdshb
  • 1,949
  • 2
  • 28
  • 40
0

This method return file names in a directory in Assets folder

 private fun getListOfFilesFromAsset(path: String, context: Context): ArrayList<String> {
            val listOfAudioFiles = ArrayList<String>()
            context.assets.list(path)?.forEach { file ->
                val innerFiles = getListOfFilesFromAsset("$path/$file", context)
                if (innerFiles.isNotEmpty()) {
                    listOfAudioFiles.addAll(innerFiles)
                } else {
                    // it can be an empty folder or file you don't like, you can check it here
                    listOfAudioFiles.add("$path/$file")
                }
            }
            return listOfAudioFiles
        }

For example you want to load music file path from sound folder

enter image description here

You can fetch all sound like this:

  private const val SOUND_DIRECTORY = "sound"


   fun fetchSongsFromAssets(context: Context): ArrayList<String> {
        return getListOfFilesFromAsset(SOUND_DIRECTORY, context)
    }
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154
0
public static String[] getDirectoryFilesRecursive(String path)
{
    ArrayList<String> result  = new ArrayList<String>();
    try
    {
        String[] files = Storage.AssetMgr.list(path);
        for(String file : files)
        {
            String filename = path + (path.isEmpty() ? "" : "/") + file;
            String[] tmp = Storage.AssetMgr.list(filename);
            if(tmp.length!=0) {
                result.addAll(Arrays.asList(getDirectoryFilesRecursive(filename)));
            }
            else {
                result.add(filename);
            }
        }
    }
    catch (IOException e)
    {
        Native.err("Failed to get asset file list: " + e);
    }
    Object[] objectList = result.toArray();
    return Arrays.copyOf(objectList,objectList.length,String[].class);
}
don kaban
  • 21
  • 1