package hyz.com;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.ImageButton;
public class AssetManagerTestActivity extends Activity
{
private EditText et1,et2;
private ImageButton ib;
//Android 除了提供/res目录存放资源文件外,在/assets目录也可以存放资源文件,
//而且/assets目录下的资源文件不会在R.java自动生成ID,所以读取/assets目录下的文件必须指定文件的路径。
//我们可以通过AssetManager 类来访问这些文件。
private AssetManager am;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et1 = (EditText)findViewById(R.id.et1);
et2 = (EditText)findViewById(R.id.et2);
ib = (ImageButton)findViewById(R.id.ib);
am = getAssets();
String[] files = null;
try
{
//将assets下File文件夹下的所有文件和文件夹名保存至files数组
files = am.list("File");
}
catch (IOException e)
{
e.printStackTrace();
}
int i = 0;
String str = "";
for(;i<files.length;i++)
str +=files[i]+",";
et1.setText(str);
InputStream inputStream = null ;
try
{
/*
* open (String filename,int accessMode)使用一个精确的访问模式来打开当前包的一个资产,
* 返回输入流,即由此读取了这个包的资产的内容。这里所说的资产是放置在assets目录下的文件资产。
* accessmode的值可以为:ACCESS_BUFFER,ACCESS_RANDOM,ACCESS_STREAMING,ACCESS_UNKNOWN其中的一个。
*/
inputStream = am.open("File/read.txt");
}
catch (IOException e) {}
String s = getTextFromAssetFile(inputStream);
et2.setText(s);
Bitmap bgImg = getImageFromAssetFile( "background.png" );
ib.setImageBitmap(bgImg);
}
private String getTextFromAssetFile(InputStream inputStream)
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buf[] = new byte [1024];
int len;
try
{
while ((len = inputStream.read(buf)) != -1)
{
outputStream.write(buf, 0, len);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {}
return outputStream.toString();
}
private Bitmap getImageFromAssetFile(String fileName)
{
Bitmap image = null ;
try
{
InputStream is = am.open(fileName);
image = BitmapFactory.decodeStream(is);
is.close();
}catch (Exception e){}
return image;
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<EditText android:id="@+id/et1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<EditText android:id="@+id/et2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<ImageButton
android:id="@+id/ib"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>