简体   繁体   English

在我的应用程序的资产目录中列出所有文件和文件夹(以及子文件夹),并检查资产是文件还是文件夹

[英]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. 我想检查我的Android应用程序的Assets目录中的资产是文件还是目录。

I have already tried every solution available anywhere on internet including StackOverflow. 我已经尝试了Internet上任何可用的每种解决方案,包括StackOverflow。

Most of the solutions use 大多数解决方案使用

File myFile = new File(path);

then check for myFile.isDirectory(); 然后检查myFile.isDirectory(); or myFile.isFile(); myFile.isFile();

But it works only if I have my files and directories anywhere else other than under the Assets directory. 但是,只有当我的文件和目录位于Assets目录下以外的其他位置时,它才起作用。

Any suggestions will be highly appreciated. 任何建议将不胜感激。

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. 这是我的问题的解决方案,我发现工作100%列出了所有目录和文件,甚至包括子目录和子目录中的文件。 It also works for multiple levels. 它还适用于多个级别。

Note: In my case 注意:就我而言

  1. Filenames had a . 文件名有一个。 in them. 在他们中。 ie .htm .txt etc 即.htm .txt等
  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 谢谢

Instead of letting a dot in a name determine what should happen you should check if it is a file or a directory. 与其让名称中的点确定应该发生的事情,不如检查它是文件还是目录。 Make your own isDirectory(name) function by trying to open an InputStream for the file/directory. 通过尝试打开文件/目录的InputStream来制作自己的isDirectory(name)函数。 If you succeed it is a file. 如果成功,它将是一个文件。 If you get an exception its a directory. 如果出现异常,则为目录。 Dont forget to close the stream when done. 完成后不要忘记关闭流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM