Список файлов в папке с ресурсами и вложенных папках
У меня есть несколько папок с файлами HTML в папке "assets" в моем проекте Android. Мне нужно показать эти файлы HTML из подпапок активов в списке. Я уже написал код о создании этого списка.
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 doing here
b.putString("defStrID", itemname);
intent.putExtras(b);
//start Intent
startActivity(intent);
}
});
Ответы
Ответ 1
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;
}
Вызовите listAssetFiles с корневым именем папки вашего ресурса.
listAssetFiles("root_folder_name_in_assets");
Если корневая папка является папкой с активами, тогда вызовите ее с помощью
listAssetFiles("");
Ответ 2
попробуйте это, он будет работать в вашем случае
f = getAssets().list("");
for(String f1 : f){
Log.v("names",f1);
}
В приведенном выше фрагменте будет отображаться содержимое корня ресурса.
Например... если ниже представлена структура актива.
assets
|__Dir1
|__Dir2
|__File1
Выход фрагмента будет...
Dir1 Dir2 File1
Если вам нужно содержимое каталога Dir1
Передайте имя каталога в функции списка.
f = getAssets().list("Dir1");
Ответ 3
Надеюсь, что эта помощь:
следующий код скопирует всю папку и ее содержимое и содержимое подпапки в папку sdcard:
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();
}
Ответ 4
Вот решение моей проблемы, которое я обнаружил, работая на 100%, перечисляя все каталоги и файлы, даже подкаталоги и файлы в подкаталогах.
Примечание. В моем случае
- Имена файлов имели. в них. то есть .htm.txt и т.д.
Имен каталогов не было. в них.
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
Спасибо
Ответ 5
Основано на ответе @Kammaar. Этот код котлина сканирует дерево файлов на наличие листьев:
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
}
Ответ 6
я думаю, что лучше всего проверять, является ли файл проверкой dir или нет, альтернативная попытка, ловить!
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;
}