1. 读取资源文件

    资源文件一般放到assets目录下,读取方法如下:

    AssetManager assetManager = context.getAssets();

    InputStream inputStream = assetsManager.open("dir/filename.text");

    示例代码如下:

    package com.example.assetstest;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.UnsupportedEncodingException;import android.os.Bundle;import android.app.Activity;import android.content.res.AssetManager;import android.view.Menu;import android.widget.TextView;public class AssetsTest extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_assets_test);        TextView textView = (TextView)findViewById(R.id.textView);                                                                                               AssetManager assetManager = getAssets();        InputStream inputStream = null;        try {            inputStream = assetManager.open("text/text.txt");            String text = loadTextFile(inputStream);            textView.setText(text);        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }    private String loadTextFile(InputStream inputStream) throws IOException {        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();        byte[] bytes = new byte[4096];        int len = 0;        while ((len = inputStream.read(bytes)) > 0) {            byteArrayOutputStream.write(bytes, 0, len);            }        return new String(byteArrayOutputStream.toByteArray(), "UTF8");    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.assets_test, menu);        return true;    }}

  2. 访问外部存储

    访问SD卡上的文件一般需要先判断外部存储空间的状态,如果状态为Environment.MEDIA_MOUNTED,则表示状态正常,然后需要获取根目录名称并对文件进行操作。

    示例代码如下:

    boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); //判断sd卡是否存在if (sdCardExist){File sdDir = Environment.getExternalStorageDirectory();//获取跟目录}