在android中资源文件的存放和读取
- 在main文件下创建一个asset文件夹,将所需的文件存放其中。
- 利用Context.getAssets()来获取一个AssetManager对象,该对象会与asset文件夹相关联,通过open(filePath),可以获取对应路径的文件的inputStream.
源码展示
context.getAssets()
/**
* Returns an AssetManager instance for the application's package. 返回应用程序包的AssetManager实例。
* <p>
* <strong>Note:</strong> Implementations of this method should return
* an AssetManager instance that is consistent with the Resources instance
* returned by {@link #getResources()}. For example, they should share the
* same {@link Configuration} object.
*
* @return an AssetManager instance for the application's package
* @see #getResources()
*/
public abstract AssetManager getAssets();
InputStream stream = manager.open(filePath);
/**
* Open an asset using ACCESS_STREAMING mode. This provides access to
* files that have been bundled with an application as assets -- that is,
* files placed in to the "assets" directory.
* 使用ACCESS_STREAMING模式打开资产。
这提供了访问与应用程序捆绑在一起的文件作为资产-即,文
件放置在“资产”目录中。
*
* @param fileName The name of the asset to open. This name can be hierarchical.
*
* @see #open(String, int)
* @see #list
*/
public @NonNull InputStream open(@NonNull String fileName) throws IOException {
return open(fileName, ACCESS_STREAMING);
}
将资源文件的内容读入到对象中
public static String getJsonFromAssets (Context context, String filePath){
StringBuilder stringBuilder = new StringBuilder();
AssetManager manager = context.getAssets();
try {
InputStream stream = manager.open(filePath);
BufferedReader reader= new BufferedReader(new InputStreamReader(stream));
String data;
while ((data = reader.readLine())!= null){
stringBuilder.append(data);
}
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
本文介绍了在Android应用中如何管理和读取资源文件。首先,在main目录下创建一个asset文件夹,然后将需要的文件放入其中。接着,通过Context的getAssets()方法获取AssetManager对象,该对象用于与asset文件夹交互。使用AssetManager的open()方法可以打开指定路径的文件并获取InputStream。最后,提供了一个示例方法getJsonFromAssets(),用于将asset中的文件内容读取为字符串。这种方法常用于加载JSON或其他文本数据。
1256

被折叠的 条评论
为什么被折叠?



