关于Android中res等几种文件通过InputStream方式读入工程中
发布时间:2023-05-15 18:49:31
Android中res文件夹下存放着各种资源文件,如布局文件、图片资源、字符串资源等。这些资源文件有时需要在程序中进行读取操作,比如动态设置布局、使用资源图片等。本文主要介绍如何通过InputStream方式读取Android工程中的res等几种文件。
一、读取字符串资源文件
Android中的字符串资源文件通常存放在res/values/strings.xml文件中,可以通过如下代码读取:
InputStream inputStream = getContext().getResources().openRawResource(R.raw.strings);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1) {
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
String str = byteArrayOutputStream.toString();
其中R.raw.strings表示在res/raw目录下的strings.xml文件。
二、读取图片资源文件
有时候我们需要在程序中使用图片资源,在Android中图片文件一般存放在res/drawable目录下,可以通过如下代码读取:
InputStream inputStream = getContext().getResources().openRawResource(R.drawable.image); Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, null); imageView.setImageBitmap(bitmap);
其中R.drawable.image为图片资源的ID,imageView为需要设置图片的ImageView控件。
三、读取布局文件
布局文件通常存放在res/layout目录下,有时需要进行动态的布局,可以通过如下代码读取布局文件:
InputStream inputStream = getContext().getResources().openRawResource(R.layout.layout);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
try {
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append('
');
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
String layoutXml = stringBuilder.toString();
其中R.layout.layout表示在res/layout目录下的布局文件,layoutXml为读取到的布局文件内容。
四、读取音频、视频等资源文件
音频、视频等资源文件一般存放在res/raw目录下,可以通过如下代码读取:
InputStream inputStream = getContext().getResources().openRawResource(R.raw.audio);
byte[] buffer = new byte[1024];
int bytesRead;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
byte[] audioData = byteArrayOutputStream.toByteArray();
其中R.raw.audio表示在res/raw目录下的音频文件,audioData为读取到的音频文件内容。
以上就是通过InputStream方式读取Android工程中的res等几种文件的方法,可以根据需求进行使用。
