在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();
}