从资产文件夹而不是原始文件夹加载文件

时间:2018-05-20 01:37:42

标签: android android-assets

我在raw文件夹中有一个文件,我想把它放在assets文件夹中并加载它。
我怎样才能做到这一点 ?这是我的代码和文件名是 pays_names.json

public static CountryFlagsLoader getInstance() {
    return ourInstance;
}

public void load(Context context) {
         /// load file from raw folder
    Resources resources = context.getResources();
    final InputStream inputStream = resources.openRawResource(R.raw.pays_names);
    final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

    Gson gson = new Gson();
    Type collectionType = new TypeToken<Collection<Country>>() {
    }.getType();
    Collection<Country> countries = gson.fromJson(reader, collectionType);

    for (Country country : countries) {
        countryToCode.put(country.getName().toLowerCase(Locale.ENGLISH), country.getCode());
    }
}

public Drawable getFlag(Context context, String countryName) {
    String countryCode = countryToCode.get(countryName.toLowerCase(Locale.ENGLISH));

    if (countryCode != null) {
        Resources resources = context.getResources();
        final String resourceName = "flag_" + countryCode.toLowerCase();
        final int resourceId = resources.getIdentifier(resourceName, "drawable",
                context.getPackageName());
        if (resourceId != 0) {
            return resources.getDrawable(resourceId);
        }
    }
    return null;
}

2 个答案:

答案 0 :(得分:0)

final InputStream inputStream = resources.openRawResource(R.raw.pays_names);

如果文件在资产中,则只需替换为

InputStream inputStream = getAssetManager().openInputStream("pays_names.json");

为什么要最终?

答案 1 :(得分:0)

谢谢你们,我找到了解决方案,我只需改变一些行:

public void load(Context context) {
     /// load file from raw folder
    Resources resources = context.getResources();
    final InputStream inputStream = resources.openRawResource(R.raw.pays_names);
    final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

Gson gson = new Gson();
Type collectionType = new TypeToken<Collection<Country>>() {
}.getType();
Collection<Country> countries = gson.fromJson(reader, collectionType);

for (Country country : countries) {
    countryToCode.put(country.getName().toLowerCase(Locale.ENGLISH), country.getCode());
}
}

这一个

public void load(Context context) {

    AssetManager assetManager = context.getAssets();
    try {
        InputStream is = assetManager.open("pays_names");
        final BufferedReader reader = new BufferedReader(new InputStreamReader(is));


        Gson gson = new Gson();
        Type collectionType = new TypeToken<Collection<Country>>() {
        }.getType();
        Collection<Country> countries = gson.fromJson(reader, collectionType);

        for (Country country : countries) {
            countryToCode.put(country.getName().toLowerCase(Locale.ENGLISH), country.getCode());
        }
    } catch (IOException e) {

    }
}