Android,如何获取文件夹中所有文件的列表?

问题描述 投票:0回答:7

我需要 res/raw/ 中所有文件的名称(字符串)

我尝试过:

File f = new File("/"); 
String[] someFiles = f.list();

看起来根目录是android模拟器的根目录...而不是我的电脑根目录。这很有意义,但并不能真正帮助我找出原始文件夹所在的位置。

更新:感谢所有精彩的回复。看来其中一些方法确实有效,但只成功了一半。也许更详细的描述会有所帮助

我想获取原始文件夹中的所有 mp3 文件,以便获取所有名称,然后将它们添加到 URI 以按以下方式播放随机 MP3...

String uriStr = "android.resource://"+ "com.example.phone"+ "/" + "raw/dennis";
Uri uri = Uri.parse(uriStr);
singletonMediaPlayer = MediaPlayer.create(c, uri);

当我将“dennis.mp3”放入资产文件夹中时,它确实按预期显示,但是,使用上面的代码,我无法再访问该 MP3,除非有以下内容:

String uriStr = "android.assets://"+ "com.example.phone"+ "/" + "dennis";
Uri uri = Uri.parse(uriStr);
android android-file
7个回答
70
投票

要列出原始资产的所有名称(基本上是去掉扩展名的文件名),您可以执行以下操作:

public void listRaw(){
    Field[] fields=R.raw.class.getFields();
    for(int count=0; count < fields.length; count++){
        Log.i("Raw Asset: ", fields[count].getName());
    }
}

由于实际文件在手机上后并不只是位于文件系统上,因此名称无关紧要,您需要通过分配给该资源名称的整数来引用它们。在上面的例子中,你可以这样得到这个整数:

int resourceID=fields[count].getInt(fields[count]);

这与您通过引用 R.raw.whateveryounamedtheresource 获得的 int 相同


10
投票

此代码将从 sdCard 的“New Foder”中检索所有文件。

    File sdCardRoot = Environment.getExternalStorageDirectory();
    File yourDir = new File(sdCardRoot, "New Folder");
    for (File f : yourDir.listFiles()) {
        if (f.isFile())         
        {               
           String name = f.getName();           
           Log.i("file names", name);          

        }

     }

并确保在您的manifest.xml文件中添加android SD卡写入权限


4
投票

我需要 res/raw/ 中所有文件的名称(字符串)

设备上的

res/raw/
中没有文件。这些都是资源。除了使用反射来迭代
R.raw
类的静态数据成员来获取各种 ID 名称和值之外,没有什么好的方法来迭代资源。

但并不能真正帮助我找出原始文件夹所在的位置。

作为文件夹,它仅存在于您的开发计算机上。它不是设备上的文件夹。


3
投票

您可以使用AssetManager

据我所知,您将拥有以下列表(只需尝试不同的路径):

final String[] allFilesInPackage = getContext().getResources().getAssets().list("");

2
投票

查看http://developer.android.com/reference/android/content/res/Resources.html 您通常可以使用 getResources() 获取与您的应用程序关联的 Resources 实例。

Resources 类提供对 http://developer.android.com/reference/android/content/res/AssetManager.html 的访问(请参阅 getAssets() 方法)。 最后使用 AssetManager.list() 方法获取对打包 (apk) 文件的访问权限。 享受吧!


1
投票

Context
,你可以这样调用:

getResources().getAssets().list("thePath");

文档链接


0
投票

这里有两个 Kotlin 解决方案。

方法1

// Make sure to add this dependency in your build file
// implementation(kotlin("reflect"))

for (property in R.raw::class.staticProperties) {
    val itsName = property.name
    val itsValue = property.get() // Aka, the resource ID
}

请注意,要获取非静态属性(实例成员),请使用

staticProperties
并将对象实例传递给
memberProperties
函数调用,而不是上面的
get()

方法2

val fields = R.raw::class.java.getFields()
for (field in fields) {
    val itsName = field.name
    val itsValue = field.getInt(field) // Aka, the resource ID
}
© www.soinside.com 2019 - 2024. All rights reserved.