我的 Android 项目的“assets”文件夹中有一些包含 HTML 文件的文件夹。我需要在列表中显示资产子文件夹中的这些 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's doing here
b.putString("defStrID", itemname);
intent.putExtras(b);
//start Intent
startActivity(intent);
}
});
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("");
尝试一下,它会适合你的情况
f = getAssets().list("");
for(String f1 : f){
Log.v("names",f1);
}
上面的代码片段将显示资产根目录的内容。
例如...如果下面是资产结构..
assets
|__Dir1
|__Dir2
|__File1
片段的输出将是...... 目录 1 目录 2 文件 1
如果您需要目录Dir1的内容
在列表函数中传递目录名称。
f = getAssets().list("Dir1");
希望有帮助:
以下代码将复制所有文件夹及其内容和子文件夹的内容到SD卡位置:
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();
}
这是我的问题的解决方案,我发现它可以 100% 列出所有目录和文件,甚至子目录和子目录中的文件。
注意:就我而言
目录名称没有任何 .在他们里面。
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
谢谢
我认为最好检查文件是否为目录,或者尝试,捕获!
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;
}
基于@Kammaar 的回答。此 kotlin 代码扫描文件树中的叶子:
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
}
此方法返回 Assets 文件夹中目录中的文件名
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
}
例如您想从声音文件夹加载音乐文件路径
您可以像这样获取所有声音:
private const val SOUND_DIRECTORY = "sound"
fun fetchSongsFromAssets(context: Context): ArrayList<String> {
return getListOfFilesFromAsset(SOUND_DIRECTORY, context)
}
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);
}
@Kammaar 的答案的改进版本,在 Kotlin [递归]
fun listAssetFiles(
context: Context,
path: String,
dirCallback: ((dirPath: String) -> Unit)? = null,
fileCallback: (filePath: String) -> Unit,
): Boolean {
try {
context.assets.list(path)?.also { files ->
if (files.isNotEmpty()) {
for (file in files) {
val relativePath = if (path.isEmpty()) file else "$path${File.separatorChar}$file"
if (!listAssetFiles(context, relativePath, dirCallback,fileCallback))
fileCallback.invoke(relativePath) else dirCallback?.invoke( relativePath)
}
} else return false
}
} catch (e: IOException) {return false}
return true
}
使用方法:
listAssetFiles(getApplication(), ""){Log.e("TAG", "File found -> $it")}
另一个示例,用于检索单独的文件和文件夹列表:
val fileList = mutableListOf<String>()
val folderList = mutableListOf<String>()
listAssetFiles(
context = getApplication(),
path = "sample_folder",
dirCallback = {folderList.add(it)},
fileCallback = {fileList.add(it)})