如何从字符串中获取android中的资源

时间:2017-07-01 11:20:12

标签: java android json

我有一个json文件,其中包含我想在我的代码中使用的资源名称,但我不知道如何? Json文件

{
file1: "file1.xml",
file2: "file2.xml"
...
}

我需要做这样的事情

InputStream f1 = this.getResources().openRawResource(R.raw.file1);
InputStream f2 = this.getResources().openRawResource(R.raw.file2);
InputStream f3 = this.getResources().openRawResource(R.raw.file3);

在我的代码中进一步使用它

2 个答案:

答案 0 :(得分:1)

试试这个:

String rawFileName = "file1.xml"
int resId = context.getResources().getIdentifier(rawFileName, "raw", context.getPackageName());
InputStream f1 = this.getResources().openRawResource(resId);`

答案 1 :(得分:1)

尝试使用Resources#getIndentifier()方法,但您可能需要删除文件扩展名:

public static int getIdentifierForRawXmlFileName(Context context, String fileName) {
    final Resources res = context.getResources();
    final String packageName = context.getPackageName();
    if (fileName.endsWith(".xml") {
        fileName = fileName.subString(0, fileName.lastIndexOf(".xml"));
    }
    return res.getIdentifier(fileName, "raw", packageName);
 }

您可以将其用作:

final int rawId = getIndetifierForRawXmlFileName(this, "file1.xml");
final InputStream is = getResources().openRawResource(rawId);
相关问题