0

我正在尝试使用以下代码读取我的 res/raw 目录中的文本文件:

public String fetchParam(String name, int index){
    InputStream is = getResources().openRawResource(R.raw.name);
    InputStreamReader isreader = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isreader);
    ...
}

问题在于“R.raw.name”,其中名称没有被解释为变量,而是作为名为“name”的 R.raw 类的成员。那么我该如何获取 R.raw.[name 传入的任何内容]?

4

1 回答 1

2

First off, i think I should say that if you're trying to access your resources like this, you're probably going about this the wrong way. The R class should not generally be used in this way.

However, if you really need to do what you're trying to do, you could use reflection. Note: This is not recommended as it uses a lot of overhead and will slow down you're application if used often.

Here's a code sample:

try
{
    int itemId = R.raw.class.getField(name).getInt(null);
    InputStream is = getResources().openRawResource(itemId);
    InputStreamReader isreader = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isreader);
} 
catch (NoSuchFieldException ex)
{
    // Handle
}
catch (IllegalAccessException ex)
{
    // Handle
}

Hope this helps :)

于 2013-10-21T00:52:16.987 回答