android 文件读取(assets)

android 文件读取(assets)

2023年7月7日发(作者:)

android 文件读取(assets)

assets文件夹资源的访问

assets文件夹里面的文件都是保持原始的文件格式,需要用AssetManager以字节流的形式读取文件。

1. 先在Activity里面调用getAssets() 来获取AssetManager引用。

2. 再用AssetManager的open(String fileName, int

accessMode) 方法则指定读取的文件以及访问模式就能得到输入流InputStream。

3. 然后就是用已经open file 的inputStream读取文件,读取完成后记得() 。

4.调用() 关闭AssetManager。

需要注意的是,来自Resources和Assets 中的文件只可以读取而不能进行写的操作

以下为从Raw文件中读取:

代码

public String getFromRaw(){

try {

InputStreamReader inputReader = new

InputStreamReader( getResources().openRawResource(1));

BufferedReader bufReader = new

BufferedReader(inputReader);

String line=""; String Result="";

while((line = ne()) != null)

Result += line;

return Result;

} catch (Exception e) {

tackTrace();

}

}

以下为直接从assets读取

代码

public String getFromAssets(String fileName){

try {

InputStreamReader inputReader = new

InputStreamReader( getResources().getAssets().open(fileName) );

BufferedReader bufReader = new

BufferedReader(inputReader);

String line="";

String Result="";

while((line = ne()) != null)

Result += line;

return Result;

} catch (Exception e) {

tackTrace();

}

}

当然如果你要得到内存流的话也可以直接返回内存流! 接下来,我们新建一个工程文件,命名为AssetsDemo。

然后建立一个布局文件,如下,很简单,无需我多介绍,大家一看就明白。

然后呢,我从网上找了段文字,存放在assets文件目录下,取名为 这就是今天我们要读取的文件啦。 这个.txt文件,我们可以直接双击查看。如下所示。

接下来,就是今天的重头戏,Android读取文件的核心代码。就直接贴代码了。

package ;

import tream;

import ngUtils;

import ty;

import ;

import ;

import ew;

public class AssetsDemoActivity extends Activity {

public static final String ENCODING = "UTF-8";

TextView tv1;

@Override

public void onCreate(Bundle savedInstanceState) { te(savedInstanceState);

setContentView();

tv1 = (TextView)findViewById(1);

tColor();

tSize(25.0f);

t(getFromAssets(""));

}

//从assets 文件夹中获取文件并读取数据

public String getFromAssets(String fileName){

String result = "";

try {

InputStream in = getResources().getAssets().open(fileName);

//获取文件的字节数

int lenght = ble();

//创建byte数组

byte[] buffer = new byte[lenght];

//将文件中的数据读到byte数组中

(buffer);

result = ing(buffer, ENCODING);

} catch (Exception e) {

tackTrace();

}

return result;

}

}

这里是mainfest文件。

package=""

android:versionCode="1"

android:versionName="1.0">

android:label="@string/app_name">

android:label="@string/app_name">

android:name="ER" />

最后,我们运行一下程序。

发布者:admin,转转请注明出处:http://www.yc00.com/xiaochengxu/1688678508a161816.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信