如何从raw文件夹到listview获取文件?

Dew*_*die 4 mp3 android list

喜欢这个代码..

public class SongsManager {
// SDCard Path
final String MEDIA_PATH = new String("/sdcard/");//this will I switch to raw folder..

private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

// Constructor
public SongsManager(){

}

/**
 * Function to read all mp3 files from sdcard
 * and store the details in ArrayList
 * */
public ArrayList<HashMap<String, String>> getPlayList(){
    File home = new File(MEDIA_PATH);

    if (home.listFiles(new FileExtensionFilter()).length > 0) {
        for (File file : home.listFiles(new FileExtensionFilter())) {
            HashMap<String, String> song = new HashMap<String, String>();
            song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
            song.put("songPath", file.getPath());

            // Adding each song to SongList
            songsList.add(song);
        }
    }
    // return songs list array
    return songsList;
}
Run Code Online (Sandbox Code Playgroud)

但是从原始文件中读取......

Esp*_*ver 7

试试看:

public void getRawFiles(){
    Field[] fields = R.raw.class.getFields();
    // loop for every file in raw folder
    for(int count=0; count < fields.length; count++){

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

        // Use that if you just need the file name
        String filename = fields[count].getName();

        // Use this to load the file
        try {
            Resources res = getResources();
            InputStream in = res.openRawResource(rid);

            byte[] b = new byte[in.available()];
            in.read(b);
            // do whatever you need with the in stream
        } catch (Exception e) {
            // log error
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,也许与你的问题并不完全相关,但如果你想从SD卡读取,你不应该写一个硬编码的路径.它不适用于许多设备.你应该使用它:

String sdcard = Environment.getExternalStorageDirectory();
Run Code Online (Sandbox Code Playgroud)

更新:

看起来您正在尝试使用文件名及其相应路径构建哈希映射.这对于SD卡中的通用文件可能有意义,但它不适用于raw或assets文件夹中的文件.这是因为它们包含在你的apk中,它基本上是一个zip文件.这意味着访问apk中的文件并不容易(尽管可以使用一些解压缩工具).

既然你没有说明你需要什么,很难知道.您可以使用上面的代码获取原始文件夹中的文件名,并将其显示在列表中.此外,您可以保存资源ID.如果用户单击某个项目,您将获得该项目的资源ID,并使用InputStream加载该文件,如上面的代码所示.您不能像在示例中那样使用File类(因为正如我所说,它们不是真正的文件),但您可以使用android Resources类通过InputStream读取原始资产.