1. File read mode
Assetmanager.open (String filename), which returns a byte stream of type Inputsteam, where filename must be a file, not a folder. Assetmanager The Open method of opening a resource file is an overloaded method, you can add an open int parameter, and you can do it according to the parameters.
2. resource files are folders and subdirectories that can exist
Public final string[]list (String path), which returns all the files under the current directory and the names of subdirectories. You can traverse the entire file directory recursively to achieve access to all resource files.
Mainactivity.java
Packagecn.lixyz.iotest.activity;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.EditText;ImportCN.LIXYZ.IOTEST.R;ImportCn.lixyz.iotest.util.IOFile; Public classMainactivityextendsActivityImplementsOnclicklistener {PrivateButton Bt_asset_read; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Findview (); Bt_asset_read.setonclicklistener ( This); } Public voidFindview () {Bt_asset_read=(Button) Findviewbyid (R.id.bt_asset_read); } @Override Public voidOnClick (View v) {iofile iofile; Switch(V.getid ()) { CaseR.id.bt_asset_read:iofile=NewIofile ( This); Iofile.readfromasset ( This); Break; } }}
Activity_main.xml
<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical"Tools:context= "Cn.lixyz.iotest.activity.MainActivity" > <ButtonAndroid:id= "@+id/bt_asset_read"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "Asset directory read" /></LinearLayout>
Iofile.java
PackageCn.lixyz.iotest.util;Importjava.io.IOException;ImportJava.io.InputStream;ImportAndroid.content.Context;ImportAndroid.content.res.AssetManager;ImportAndroid.util.Log; Public classiofile {Context mcontext; PublicIofile (Context context) {Mcontext=context; } //read the contents of the Asset directory Public voidReadfromasset (Context context) {Try { //Get asset managerAssetmanager Assetmanager =context.getassets (); //obtaining subdirectories under the asset directory through the asset managerstring[] Filesname = assetmanager.list ("txts"); //looping through the contents of a file for(inti = 0; i < filesname.length; i++) {InputStream InputStream= Assetmanager.open ("txts/" +Filesname[i]); byte[] bytes =New byte[Inputstream.available ()]; Inputstream.read (bytes); String Str=NewString (bytes); LOG.D ("Tttt", "filesname[i" + "content is:" +str); } } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } }}
Android Notes (49) access to resources in Android--asset