Android API之Assets下文件操作

来源:互联网 发布:键鼠套装 知乎 编辑:程序博客网 时间:2024/06/05 10:44
public class ReadAssetActivity extends Activity {    private TextView mTextView;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.read_asset);        initViews();        readAssetsData();        listAssetsFiles("fonts");// 列出文件目录    }    private void readAssetsData() {        InputStream is = null;        try {            // 读取Assets文件夹下对应文件的输入流            is = getAssets().open("asset_test.txt");            // 获取文件输入流的总大小            int size = is.available();            // 把整个文件流放到一个Byte[]缓冲区            byte[] buffer = new byte[size];            is.read(buffer);            is.close();            // 将缓冲区数据转换为字符串            String text = new String(buffer);            mTextView.setText(text);        } catch (IOException e) {            e.printStackTrace();        } finally {            try {                if (is != null) {                    is.close();                }            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }    }    private void initViews() {        mTextView = (TextView) findViewById(R.id.text);    }    /**     * 获取Assets下指定文件夹下文件数量 情况     *      * @description:     * @author ldm     * @date 2016-4-27 上午9:25:54     */    private void listAssetsFiles(String filePath) {        AssetManager am = getAssets();        String[] fileName;        try {            fileName = am.list(filePath);            if (fileName.length > 0) {                for (int i = 0; i < fileName.length; i++) {                    Log.e("ldm", String.format("在" + filePath                            + "中文件路下有:[%d] 文件数量", fileName.length));                }            }        } catch (IOException e) {            e.printStackTrace();        }    }}
0 0
原创粉丝点击